Skip to content

Instantly share code, notes, and snippets.

@jessehouchins
Last active August 29, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessehouchins/8715846 to your computer and use it in GitHub Desktop.
Save jessehouchins/8715846 to your computer and use it in GitHub Desktop.
Convenience wrapper for translating delegated events to directly bound events in Backbone views. This was developed specifically for converting delegated `mouseover` events to bound `scroll` events, but could be used in other cases as well.
var $ = require('jquery')
// This helper allows you to translate events that DO bubble
// to directly bound events for event typess that DO NOT
// (like scroll) using either syntax below:
// var translateEventTo = require('translateEventTo')
// ...then in the view class definition...
// events : {
// 'mouseover .selector1' : translateEventTo('scroll', 'viewMethod'),
// 'mouseover .selector2' : translateEventTo('scroll', customHandler)
// }
function translateEventTo(eventName, method) {
var namespace = typeof method === 'string' ? method : newNamespace()
return function(e) {
if (typeof method !== 'function') method = this[method]
replaceWithBoundEvent(e, eventName, method.bind(this), namespace)
}
}
// Provides a unique namespace for all translated events
var counter = 1
function newNamespace() {
return 'translateEventTo' + counter++
}
// Removes a delegated event and binds the handler directly
// to the elements mathching the original selector.
function replaceWithBoundEvent(e, newType, newHandler, newNamespace) {
var handleObj = e.handleObj
var selector = handleObj.selector
var origNamespace = '.' + handleObj.namespace
var origEvent = handleObj.origType + origNamespace
var origHandler = handleObj.handler
var newEvent = newType + origNamespace + '_' + newNamespace
$(e.delegateTarget)
.off(origEvent, selector, origHandler)
.find(selector)
.off(newEvent)
.on(newEvent, newHandler)
}
module.exports = translateEventTo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment