Skip to content

Instantly share code, notes, and snippets.

@dotmaster
Created July 7, 2011 21:34
Show Gist options
  • Save dotmaster/1070599 to your computer and use it in GitHub Desktop.
Save dotmaster/1070599 to your computer and use it in GitHub Desktop.
bindAll
//this is a generic function which should be moved to a Baseclass of Backbone or a Backbone extension
autoBind =
{
autoBind: function () {
var self = this;
var funcs = _.functions(this.constructor.prototype);
var protoFuncs = ['autoBind', 'constructor'].concat(
_.functions(Backbone.Collection.prototype),
_.functions(Backbone.Model.prototype));
_.functions(Backbone.View.prototype));
_.each(funcs, function(f){
if(f.charAt(0) !=='_' && _.indexOf(protoFuncs, f) === -1)
{
self[f] = _.bind(self[f], self);
}
});
}
}
_.extend (Backbone.Collection.prototype, autoBind);
_.extend (Backbone.Model.prototype, autoBind);
_.extend (Backbone.View.prototype, autoBind);
var MovieView = Backbone.View.extend({
initialize: function (args) {
this.autoBind();
this.model.bind('change:title', this.changeTitle);
this.model.bind('change:name', this.changeName);
},
changeTitle: function () {
this.$('.title').text(this.model.get('title'));
},
changeName: function () {
this.$('.name').text(this.model.get('name'));
},
_doNotBindMe: function () {
//this here is pointing to the caller
}
})
var MovieView = Backbone.View.extend({
initialize: function (args) {
_.bindAll(this, 'changeTitle', 'changeName');
this.model.bind('change:title', this.changeTitle);
this.model.bind('change:name', this.changeName);
},
changeTitle: function () {
this.$('.title').text(this.model.get('title'));
},
changeName: function () {
this.$('.name').text(this.model.get('name'));
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment