Skip to content

Instantly share code, notes, and snippets.

@esamattis
Last active October 22, 2021 20:41
Show Gist options
  • Save esamattis/5927950 to your computer and use it in GitHub Desktop.
Save esamattis/5927950 to your computer and use it in GitHub Desktop.
Use listenTo/stopListening from Backbone.js with any DOM element
/**
* Use listenTo/stopListening from Backbone.js with any DOM element
*
* Example:
*
* view.listenTo(asEvents(window), "resize", handler);
*
* and the listener will be remove automatically on view.remove() or
* view.stoplistening()
*
*
* @param {DOM Element}
* @return {Backbone Events style object}
**/
function asEvents(el) {
// Unwrap jQuery
if (typeof el.get === "function") el = el.get(0);
var listeners = [];
return {
on: function(event, handler, context) {
el.addEventListener(event, handler, false);
listeners.push({
args: [event, handler],
context: context
});
},
off: function(event, handler, context) {
listeners = listeners.filter(function(listener) {
if (listener.context === context) {
el.removeEventListener.apply(el, listener.args);
return true;
}
});
}
};
}
module.exports = asEvents;
@andyscott12
Copy link

how would you go about using this so its available in requireJS ? i.e. so like wrapping in

define(function() {
});

then being able to use it within backbone views like

view.listenTo(asEvents(window), "resize", handler);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment