Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Last active December 27, 2015 01:29
Show Gist options
  • Save thomasboyt/7245382 to your computer and use it in GitHub Desktop.
Save thomasboyt/7245382 to your computer and use it in GitHub Desktop.
simplifying bindAll
var ActionsView = Backbone.View.extend({
delegateEvents: function(events) {
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
// !! This is the modified bit !!
if (!_.isFunction(method)) {
if (!!this.actions) {
method = this.actions[events[key]] || this[events[key]];
} else {
method = this[events[key]];
}
}
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
initialize: function() {
if (this.actions) {
_.bindAll.apply(undefined, [this].concat(_.keys(this.actions)));
}
}
});
var CoolView = ActionsView.extend({
events: {
'click .submit': 'submit'
}
actions: {
submit: function(evt) {
// ...
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment