copenndthagen
copenndthagen

Reputation: 50732

Use of Ember evented in a service for publishing/subscribing to events

I am using an event-bus service in my app as below;

import Evented from '@ember/object/evented';
import Service from '@ember/service';

export default Service.extend(Evented, {
  publish: function(){
    return this.trigger.apply(this, arguments);
  },
  subscribe: function(){
    this.on.apply(this, arguments);
  },
  unsubscribe: function(){
    this.off.apply(this, arguments);
  }
})

Now I consume this from my app as below. I have an event-mixin which is kind of like a wrapper as below;

export default Mixin.create({
  events: service('event-bus'),
  subscribe: function(eventName, callback){
    this.get('events').on(eventName, this, callback);
  },
  unsubscribe: function(eventName, callback){
    this.get('events').off(eventName, this, callback);
  }    
})

Also, to actually use this in a component, I have;

import events from '../mixins/event-mixin';
export default Component.extend (events, {

  eventsToListen: function(){
    return [{
      eventName: "enableBtn",
      callBack: $..proxy(this.enableBtn, this);
    }]
  }
}

I have showed few parts of the relevant code here. While I understand the Observer pattern, the actual code has me a bit confused.

Specifically, in my event-mixin, I have code like

this.get('events').on(eventName, this, callback);

However, if I look at my event-bus which is like a common f/w service which I consume, it has

subscribe: function(){
    this.on.apply(this, arguments);
}

I am confused as to there is no call made from my app directly to publish/subscribe/unsubscribe methods defined in event-bus (instead I have this.get('events').on(....))

How does it work ?

Upvotes: 0

Views: 994

Answers (1)

mistahenry
mistahenry

Reputation: 8724

The actual Ember.evented pattern uses on, off, and trigger as the main API. Your event bus service appears to be a wrapper around these functions, conforming Ember.Evented to the more generic pub/sub pattern.

The following code

publish: function(){
  return this.trigger.apply(this, arguments);
},
subscribe: function(){
  this.on.apply(this, arguments);
}

has effectively aliased trigger -> publish and on -> subscribe. Why these aliased functions are not used in your codebase is something no one but your teammates can answer (or perhaps a search through version control history). From the code you've shown, the components in your app are using the event-bus as the event source, but are using the Ember.Evented API directly.

Upvotes: 1

Related Questions