Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Forked from erkobridee/ng-pubsub-service.js
Last active October 27, 2015 18:00
Show Gist options
  • Select an option

  • Save marcelaraujo/70693c888120cdda1f4f to your computer and use it in GitHub Desktop.

Select an option

Save marcelaraujo/70693c888120cdda1f4f to your computer and use it in GitHub Desktop.
(function () {
'use strict';
function PubSubService() {
var Topics = function () {
this.topics = {};
};
Topics.prototype.subscribe = function (topic, listener) {
// Create the topic's object if not yet created
if (!this.topics.hasOwnProperty.call(this, topic)) {
this[topic] = [];
}
// Add the listener to queue
this.topics[topic].push(listener);
listener.remove = function remove() {
var index = this.topics[topic].indexOf(listener);
if (index !== -1) {
this.topics[topic].splice(index, 1);
}
index = null;
listener = null;
};
return listener.remove;
};
Topics.prototype.publish = function (topic, data) {
// If the topic doesn't exist, or there's no listeners in queue, just leave
if (!this.topics.hasOwnProperty.call(topics, topic)) {
return;
}
// Cycle through topics queue, fire!
this.topics[topic].forEach(function (item) {
item(data !== undefined ? data : {});
});
}
return new Topics();
}
angular
.module('app')
.service('PubSubService', PubSubService);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment