Listen to service events


#1

Shouldn’t it be possible to listen service events?

Here is my situation: – we have a service responsible for l10n – we use some components using 3rd party libs for UI elements which uses current locale (github-style heatmap for example) – obviously we want to rerender components when locale changed.

Easiest way to do so is to add an observer:

renderPlugin: function(){
    //complex locale-dependent logic with some third-party d3 plugin
    this.incrementProperty('renderCount');
  }.on('didReceiveAttrs').observes('locale.currentLocale')

But observers are evil

So have to use this ugly way-around:

import Ember from 'ember';

export default Ember.Component.extend({
  locale: Em.inject.service(),
  
  localeChangedSubscribe: function(){
    this.get('locale').on( 'localeChanged', this, 'localeChangedEmit');
  }.on('init'),
  
  localeChangedUnsubscribe: function(){
    this.get('locale').off( 'localeChanged', this, 'localeChangedEmit');
  }.on('willDestroyElement'),
  
  localeChangedEmit: function(){
    if (this._state === 'inDOM') {
      this.trigger('localeChanged');
    }
  },
  
  renderPlugin: function(){
    //complex locale-dependent logic with some third-party d3 plugin
  }.on('didReceiveAttrs', 'localeChanged')
});

Full example – https://ember-twiddle.com/de5c46049401311d4af070605f31f54e?openFiles=components.some-component.js%2Ctemplates.components.some-component.hbs

Is there a better idiomatic way?