Forked from dotmaster/autoBind function for Backbone.js
Created
July 10, 2011 00:57
-
-
Save jorilallo/1074110 to your computer and use it in GitHub Desktop.
bindAll
This file contains 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
//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); |
This file contains 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 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 | |
} | |
}) |
This file contains 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 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