Created
March 30, 2012 17:54
-
-
Save spikebrehm/2253376 to your computer and use it in GitHub Desktop.
Add Backbone-style events to any function's prototype
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 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 <[email protected]> | |
* 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