Skip to content

Instantly share code, notes, and snippets.

@johntimothybailey
Created February 28, 2012 19:25
Show Gist options
  • Select an option

  • Save johntimothybailey/1934552 to your computer and use it in GitHub Desktop.

Select an option

Save johntimothybailey/1934552 to your computer and use it in GitHub Desktop.
Method Scoping Workaround - Underscore
_.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;
}
});
// 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);
}
});
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();
@johntimothybailey
Copy link
Author

While helpful for Backbone's views, this is very helpful when using mixins when scoping could become an issue.
http://jsfiddle.net/johntimothybailey/27dFZ/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment