dimanche 22 mars 2020

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 ?




Aucun commentaire:

Enregistrer un commentaire