In Java, C#, Actionscript etc. Events are for classes whereas in Javascript it seems restricted to dom. I read here a sample for doing it with jQuery http://www.west-wind.com/weblog/posts/2010/May/27/NonDom-Element-Event-Binding-with-jQuery
but if I don't need jQuery and if I want to understand the mechanism how would you do it ?
at it's simplest the mechanism is something like:
function PubSub() {
this.subs = {};
this.subscribe = function(channel, sub) {
this.subs[channel] = this.subs[channel] || []; //create array for channel
this.subs[channel].push(sub);
};
this.publish = function(channel) {
var args = [].slice.call(arguments, 1); //pop off channel argument
this.subs[channel].forEach(function(sub) {
sub.apply(void 0, args); //call each method listening on the channel
});
};
}
demo here: http://jsfiddle.net/3PNtR/
-- EDIT (~5 years later) --
same simple mechanism, newer syntax
class PubSub {
constructor () {
this.subs = {}
}
subscribe (channel, sub) {
this.subs[channel] = this.subs[channel] || []
this.subs[channel].push(sub)
}
publish (channel, ...args) {
;(this.subs[channel] || []).forEach(sub => sub(...args))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With