Created
June 1, 2015 15:20
-
-
Save lsauvaget/341e541eff6aaa934513 to your computer and use it in GitHub Desktop.
Publish-Subscribe Vanilla JS
This file contains 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
//Fork of https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-plugin.html | |
// No need JQuery | |
var o = {}; | |
(function(d){ | |
// the topic/subscription hash | |
var cache = {}; | |
d.publish = function(/* String */topic, /* Array? */args){ | |
cache[topic] && [].forEach.call(cache[topic], function(element){ | |
element.apply(d, args || []); | |
}); | |
}; | |
d.subscribe = function(/* String */topic, /* Function */callback){ | |
if(!cache[topic]){ | |
cache[topic] = []; | |
} | |
cache[topic].push(callback); | |
return [topic, callback]; // Array | |
}; | |
// Disconnect a subscribed function for a topic. | |
d.unsubscribe = function(/* Array */handle){ | |
// handle: Array - The return value from a $.subscribe call. | |
var t = handle[0]; | |
cache[t] && [].forEach.call(cache[t], function(element,idx){ | |
if(element == handle[1]){ | |
cache[t].splice(idx, 1); | |
} | |
}); | |
}; | |
})(o); | |
var event = o.subscribe('test', function(){console.log('test');}); | |
o.publish('test'); | |
o.unsubscribe(event); | |
o.publish('test'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment