Last active
January 13, 2016 19:38
-
-
Save amk221/305dab89d58435086821 to your computer and use it in GitHub Desktop.
Ember.js: Easier document-level event handling
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 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); | |
} | |
} | |
}); |
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
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'); | |
} | |
} | |
} | |
}); |
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
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