Skip to content

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
simple pubsub - the angular way
'use strict';
(function() {
var mod = angular.module("", []);
//register other services here...
/* pubsub - based on*/
mod.factory('pubsub', function() {
var cache = {};
return {
publish: function(topic, args) {
cache[topic] && $.each(cache[topic], function() {
this.apply(null, args || []);
subscribe: function(topic, callback) {
if(!cache[topic]) {
cache[topic] = [];
return [topic, callback];
unsubscribe: function(handle) {
var t = handle[0];
cache[t] && d.each(cache[t], function(idx){
if(this == handle[1]){
cache[t].splice(idx, 1);
return mod;

$.each instead of d.each, and I would even replace this by a for loop to make it jQuery independant


@standup75 or replace it with angular.forEach


Problem I'm having with this is the unsubscribe. My subscribed functions are defined with in the controllers and each time the view / controller is navigated to it re-subscribes.

The cache array gets bigger and bigger without unsubscribe working so the controller is being triggered multiple times depending how many times the user has accessed the view/controller.

I've tried unsubscribing a named function on each instantiation of the view but of course in the cache array the original subscribed function is not the same reference so it this == handle[1] is never true.

I've tried anonymous, var myProcess = function() and $scope.myProcess = function but each of these declarations are not the same reference when AngularJS re-runs my controller.

Any ideas?


@NickBarton . There you have automatic unsubscriptions when the scope is destroyed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.