Created
February 28, 2012 19:25
-
-
Save johntimothybailey/1934552 to your computer and use it in GitHub Desktop.
Method Scoping Workaround - Underscore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| _.mixin({ | |
| /** | |
| * Convenience for simplifying scoping methods workaround in javascript for a given context | |
| * @param context The context where the methods are found | |
| * @param exclude An array of method names (strings) to exclude in the binding | |
| */ | |
| bindMethods: function(context,exclude){ | |
| exclude = exclude || []; | |
| _.bindAll.apply(context, [context].concat(_.difference(_.methods(context),exclude))); | |
| return context; | |
| } | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Example Using Backbone's View | |
| var MyView = new Backbone.View.extend({ | |
| name: "I don't have a name", | |
| events: { | |
| "click": "handleClick" | |
| } | |
| initialize: function ( options ){ | |
| _.bindMethods(this); | |
| }, | |
| handleClick: function(jqevent){ | |
| this.sayName(); | |
| }, | |
| sayName: function() { | |
| alert(this.name); | |
| } | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var ClickElementMixin = { | |
| initialize: function(options){ | |
| $(this.options.selector).click(this.handleSelectorClicked); | |
| }, | |
| handleSelectorClicked: function ( event ) { | |
| } | |
| } | |
| var DogMixin = { | |
| speak: function(){ | |
| console.log("woof"); | |
| console.log(this.options); | |
| } | |
| }; | |
| var BirdMixin = { | |
| fly: function(){ | |
| console.log("flying high"); | |
| } | |
| } | |
| var DogBird = function( options ){ | |
| this.options = options; | |
| } | |
| _.extend(DogBird.prototype, ClickElementMixin, DogMixin, BirdMixin, { | |
| handleSelectorClicked: function( event ) { | |
| event.preventDefault(); | |
| this.speak(); | |
| this.fly(); | |
| } | |
| }); | |
| var funnyhead = _.bindMethods(new DogBird({selector:"#summonDogBirdButton"})); | |
| funnyhead.initialize(); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While helpful for Backbone's views, this is very helpful when using mixins when scoping could become an issue.
http://jsfiddle.net/johntimothybailey/27dFZ/