Want a shortcut for subscriptions and notifying users about messages? We’ve found a way. Ember has built-in code for implementing the pub-sub pattern.

Today’s refactoring of a small part of our Ember app, responsible for connecting to PubNub to provide real-time updates, resulted in a discovery. We have a dedicated pubnub service to wrap up PubNub communication. For subscribing and notifying all interested objects about new PubNub messages, we use the pub-sub pattern. For implementation, we relied on custom, simple functions inside the service:

import Ember from 'ember';
const { Service } = Ember;

export default Service.extend({
  ...
  addListener(listener) {
    this.get('listeners').pushObject(listener);
  },

  removeListener(listener) {
    this.get('listeners').removeObject(listener);
  }

  ...
  // Then to notify listeners
  this.get('listeners').forEach((listener) => {
    listener(response.message);
  });
});

It turns out that similar functionality is already built-in inside Ember thanks to the Ember.Evented module. They only have different names: on / off instead of addListener and removeListener. But the idea is the same. Refactoring the pubnub service boiled down to removing addListener, removeListener and extending Ember.Evented:

import Ember from 'ember';
const { Evented, Service } = Ember;

export default Service.extend(Evented, {
  ...
  // Then to notify listeners
  this.trigger('receive', response.message);
});

We also had to replace our listener code for subscribing to events (simple search & replace within the project):

// Before
this.get('pubnub').addListener(callback);
this.get('pubnub').removeListener(callback);

// After
this.get('pubnub').on('receive', callback);
this.get('pubnub').off('receive', callback);

Thanks to that, we decreased the number of custom code inside the service and leveraged Ember’s power. Ember.evented also allows subscribers to be notified about a single event thanks to one, and also implements the has method to check whether there are any subscribers for a specific event. We are also able to use the same implementation for notifications about different events, i.e. disconnect, connect, etc.

Today’s Developers’ Notes were taken straight from the journal of Łukasz, our Web Application Development Team Leader. Keep an eye out for more programming tips and tricks in the future!