-
-
Save marcelaraujo/70693c888120cdda1f4f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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