Last active
December 27, 2015 01:29
-
-
Save thomasboyt/7245382 to your computer and use it in GitHub Desktop.
simplifying 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
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))); | |
} | |
} | |
}); |
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 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