Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
simple pubsub - the angular way
'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;
})();
@standup75

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

@forivall

@standup75 or replace it with angular.forEach

@NickBarton

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?

@driv

@NickBarton http://stackoverflow.com/a/21820219/469679 . 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.