Weak event listener

Kevin Gadd kevin.gadd at gmail.com
Mon Mar 25 06:28:44 PDT 2013

Most use cases I've personally seen for weak events would be satisfied by a
WeakMap of weak event target -> event handler. Having the event handler
itself be weak instead of the event target seems strange to me; it
introduces a bunch of nondeterministic behavior that isn't desirable -
sometimes you'll free all your references to a handler and it'll fire
anyway, because it hasn't been collected. It also introduces the potential
for accidentally freeing all your references to a handler and having
important behavior not run. If you get proper WRs this should be pretty
easy to build if you want it.

I think the fact that this would make GC behavior observable through the
execution/non-execution of event handlers probably makes it some sort of
security hole in the same way that WRs are, but I'm not sure - I've never
fully understood the threat posed by that information leak.


On Mon, Mar 25, 2013 at 2:55 AM, Marius Gundersen <gundersen at gmail.com>wrote:

> 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
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

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

More information about the es-discuss mailing list