public
Last active

simple pubsub - the angular way

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
'use strict';
 
(function() {
var mod = angular.module("App.services", []);
//register other services here...
/* pubsub - based on https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js*/
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] = [];
}
cache[topic].push(callback);
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 http://stackoverflow.com/a/21820219/469679 . There you have automatic unsubscriptions when the scope is destroyed.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.