Created
October 24, 2014 19:30
-
-
Save lukekarrys/5f4ebe9cb3d90b21c5dd to your computer and use it in GitHub Desktop.
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 _ = require('underscore'); | |
var inherits = require('inherits'); | |
var delegateEventSplitter = /^(\S+)\s*(.*)$/; | |
module.exports = function (SuperView) { | |
function JQueryView(attrs) { | |
SuperView.apply(this, arguments); | |
// Since $el is a derived property we cant rely on ampersand-view's | |
// internal _handleElementChange since that will delegate events | |
// before `$el` is set and we use it during delegation | |
this.on('change:$el', this._handleJQElementChange, this); | |
if (attrs.el && !this.autoRender) { | |
this._handleJQElementChange(); | |
} | |
} | |
inherits(JQueryView, SuperView); | |
JQueryView.extend = SuperView.extend; | |
return JQueryView.extend({ | |
$: function (selector, el) { | |
return $(selector, el || this.el); | |
}, | |
derived: { | |
'$el': { | |
deps: ['el'], | |
fn: function () { | |
if (this.el) { | |
return $(this.el); | |
} | |
} | |
}, | |
delegateEventNamespace: { | |
deps: ['cid'], | |
fn: function () { | |
return '.delegate-events-' + this.cid; | |
} | |
} | |
}, | |
// Currently the only thing that we need to do when our | |
// $el is ready/changed is delegate events | |
_handleJQElementChange: function () { | |
this.delegateEvents(); | |
}, | |
// `events-mixin` used by `ampersand-view` isn't compatible with | |
// `jQuery.fn.trigger` so we use our own delegate fn that uses | |
// jQuery's event system instead | |
delegateEvents: function (events) { | |
if (!(events || (events = _.result(this, 'events')))) return this; | |
this.undelegateEvents(); | |
for (var key in events) { | |
var method = this[events[key]]; | |
if (!method) continue; | |
var match = key.match(delegateEventSplitter); | |
var eventName = match[1] + this.delegateEventNamespace; | |
var selector = match[2]; | |
method = _.bind(method, this); | |
if (selector === '') { | |
this.$el.on(eventName, method); | |
} else { | |
this.$el.on(eventName, selector, method); | |
} | |
} | |
return this; | |
}, | |
undelegateEvents: function () { | |
this.$el.off(this.delegateEventNamespace); | |
return this; | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment