Created
October 11, 2012 08:43
-
-
Save emilisto/3871047 to your computer and use it in GitHub Desktop.
`onenter` event in Backbone.View
This file contains hidden or 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
/* | |
* Implements 'onenter' event for `events` object in Backbone.View. | |
* Author: Emil Stenqvist <[email protected]> | |
*/ | |
(function(global) { | |
var Backbone = global.Backbone; | |
if(!Backbone) throw "this shim needs Backbone"; | |
var delegateEvents = Backbone.View.prototype.delegateEvents; | |
delegateEventSplitter = /^(\S+)\s*(.*)$/, | |
replaceWithEvent = 'keypress'; | |
var filterFn = function(fn, ev) { | |
if(ev && ev.keyCode === 13) return fn.call(this, ev); | |
}; | |
Backbone.View.prototype.delegateEvents = function(events) { | |
events = events || this['events']; | |
if(!events) return; | |
var _events = events; | |
// Plugin works by identifying `onenter` events and overriding them with a | |
// `keypress` event with the same selector but a filtering callback that | |
// checks for the ENTER keycode before calling the real callback. | |
for(var key in events) { | |
var match = key.match(delegateEventSplitter), | |
eventName = match[1], selector = match[2]; | |
if(eventName === 'onenter') { | |
var method = events[key]; | |
if (!_.isFunction(method)) method = this[method]; | |
_events[replaceWithEvent + ' ' + match[2]] = _.bind(filterFn, this, method); | |
delete _events[key]; | |
} | |
} | |
return delegateEvents.call(this, _events); | |
}; | |
}).call(this, this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment