Search code examples
actionscript-3eventsactionscriptweak-references

Problem with event listener added by a weak reference in ActionScript


My problem is basically as follows. There is an instance of a class extending EventDispatcher. Everything goes well when I add event listener to the object like this:

myObject.addEventListener('eventName', someFunction, false, 0, false);

But something changes when event listener is added by a weak reference:

myObject.addEventListener('eventName', someFunction, false, 0, true);

Now someFunction is not called even though the line containing dispatchEvent('eventName') is being executed just like before (and there is an external reference to myObject as well).

The application I’m developing is quite complex so, unfortunately, I can’t post the exact code.


Solution

  • You are misunderstaning how GC works, I think. Using a weak reference will not pin down myObject. It could (possibly, not necessarily) prevent the scope in which the handler is declared to be collected (as long as myObject itself is alive). Hence, the callback itself could be collected, causing it not to be executed. It seems this is the case here, according to your description.

    So your goal is to avoid that the scope declaring someFunction is collected. One way could be actually using a hard ref (if you ask me, weak refs are a bad idea, anyway). There may be others, but I don't know how your app is structured, so I can't say much.

    Edit to address a comment.

    GC wise, event handling is not different from the general case. When you add a listener, you're passing a reference to the dispatcher (the reference is the scope that in which the listener is declared). The dispatches stores this reference so it can execute the callback when neccesary. It's really not that different from this:

    myObject.keepThisReference = someFunction;
    

    Now, myObejct has a reference to someFunction. So, as long as myObject is alive, someFunction will be alive too (unless you set someFunction as a weak ref).

    So, to answer the question in your comment (an object is not referenced anywhere else but has an event listener attached), given this scenario:

    myObject.addEventListener('someEvent',someFunction);
    

    If myObject doesn't have any other reference and goes out of scope, it is collectable.