Skip to content

Instantly share code, notes, and snippets.

@spikebrehm
Created March 30, 2012 17:54
Show Gist options
  • Save spikebrehm/2253376 to your computer and use it in GitHub Desktop.
Save spikebrehm/2253376 to your computer and use it in GitHub Desktop.
Add Backbone-style events to any function's prototype
/**
* This is intended to be a simple behavior mixin that allows Backbone-style event delegation to be added to any object's prototype.
*
* Use:
*
* function MyView(){ this.$el = $('#my_view'); this.delegateEvents(); }
* $.extend(MyView.prototype, Eventable);
* MyView.prototype.events = {'click a.close': 'close'};
* MyView.prototype.close = function(){ this.$el.hide(); }
*
* Notes
* * You have to manually call this.delegateEvents() in the constructor or on initialize.
* * It expects a this.$el jQuery object to exist or a this.el DOM element.
*
* @author Spike Brehm <spike@airbnb.com>
* Brought to you with love by Airbnb.
*/
(function(exports, $){
var Eventable = {
delegateEvents: function(){
if (!this.events) return;
var eventSplitter = /^(\S+)\s*(.*)$/;
for (var key in this.events) {
var method = this[this.events[key]];
if (!method) throw 'Event "' + this.events[key] + '" does not exist';
var match = key.match(eventSplitter);
var eventName = match[1], selector = match[2];
method = $.proxy(method, this);
eventName += '.delegateEvents';
var $el = this.$el || $(this.el);
if (selector === '') {
$el.bind(eventName, method);
} else {
$el.delegate(selector, eventName, method);
}
}
}
};
exports.Eventable = Eventable;
})(window, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment