Skip to content

Instantly share code, notes, and snippets.

@justinramel
Created October 28, 2015 13:19
Show Gist options
  • Save justinramel/2e003703c50446e4aa5a to your computer and use it in GitHub Desktop.
Save justinramel/2e003703c50446e4aa5a to your computer and use it in GitHub Desktop.
Ember - Better event pattern
Tip picked up from A lap around the Ember source code with Yehuda Katz
https://www.youtube.com/watch?v=RN_kVPga9y8
Use:
import service from 'ember/injections';
import on from 'ember/decorators';
export default Ember.Component.extend({
locale: service('locale'),
on('locale.localeChanged', function(newLocale) {
// handles registration and destruction!
// no memory leaks and no need to register init and willDestroy
},
////////// NOT NEEDED
init() {
this._super(...arguments);
this.locale.on('localeChanged', newLocale => this.localeDidChange(newLocale));
},
willDestroy() {
this.locale.off('localeChanged');
}
//////////
});
//app/services/locale.js
export default Ember.Service.extend(Ember.Evented, {
init() {
this._super(...arguments);
// initialize locales from localStorage (or URL string)
},
currentLocale() {
return ...; // do stuff!
},
changeLocale(newLocale) {
this.trigger('localeChanged', newLocale);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment