Skip to content

Instantly share code, notes, and snippets.

@amk221
Last active January 13, 2016 19:38
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 amk221/305dab89d58435086821 to your computer and use it in GitHub Desktop.
Save amk221/305dab89d58435086821 to your computer and use it in GitHub Desktop.
Ember.js: Easier document-level event handling
var app = Ember.Application.create();
app.DocumentEventsMixin = Ember.Mixin.create({
$doc: $(document),
documentCallbacks: {},
addDocumentEvents: function() {
this.eachDocumentEvent(function(name, callback) {
this.$doc.on(name, callback);
}.bind(this));
}.on('didInsertElement'),
removeDocumentEvents: function() {
this.eachDocumentEvent(function(name) {
this.$doc.off(name);
}.bind(this));
}.on('willDestroyElement'),
eachDocumentEvent: function(callback) {
var funcs = this.get('documentCallbacks');
for (var eventName in funcs) {
var id = this.get('elementId');
var name = '%@.doc-%@'.fmt(eventName, id);
var func = Ember.run.bind(this, funcs[eventName]);
callback(eventName, func);
}
}
});
app.FooBarComponent = Ember.Component.extend(app.DocumentEventsMixin, {
classNames: ['foo-bar'],
documentCallbacks: {
click: function(e) {
if (e.target === this.get('element')) {
console.log('Clicked inside, open foo-bar');
} else {
console.log('Clicked outside, close foo-bar');
}
}
}
});
app.BazQuxComponent = Ember.Component.extend(app.DocumentEventsMixin, {
classNames: ['baz-qux'],
documentCallbacks: {
keyup: function() {
console.log('Key up, handle keyboard shortcut for baz-qux');
},
scroll: function() {
console.log('Scrolled, handle infinite scrolling for baz-qux');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment