Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to addEventListener to non dom elements in Javascript?

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 ?

like image 635
user310291 Avatar asked Jun 03 '11 16:06

user310291


1 Answers

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))
    }
}
like image 134
dtudury Avatar answered Oct 09 '22 04:10

dtudury