Weak event listener

Marius Gundersen gundersen at gmail.com
Mon Mar 25 02:55:19 PDT 2013


I tried posting this before, but it seems to have gotten lost on the
internet.

One thing which is impossible to make in JavaScript today is a weakly
referenced event listener system. In such a system an event listener is not
strongly referenced by the event system, so events are only dispatched to
it as long as another object holds a reference to it. For example:


//some weak event system, could be global or created with constructor
var events = new WeakEventSystem();

(function(){
    //This object only exists inside this IIFE, not outside it
    var myObject = {
        handler: function(event){
            console.log("handle event: " + event);
        }
    };

    //add a listener to events, but events only has a weak reference to it
    events.addEventListener("someEvent", myObject.handler);

    //the following causes the handler above to be called, resulting in
output on the console
    events.dispatchEvent("someEvent", {params:"someParams"});

})();

//myObject does not exist anymore
//the following does not output anything on the console
events.dispatchEvent("someEvent", {params:"someParams"});

In this example the event system does not hold a strong reference to the
listener/handler function, so if nothing else has a reference to the
handler function, it is garbage collected.

Any thoughts on this, as an alternative to the more general (and low level)
weak references?

Marius Gundersen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130325/c8d1d9a5/attachment.html>


More information about the es-discuss mailing list