:::: MENU ::::

Robotlegs Gotcha #4 – RelaxedEventMap and unmapListenersFor()

I ran into an issue today where I was receiving multiple events from a single view component. I did a little digging and quickly discovered it was due to the fact that my view mediator was using the RelaxedEventMap and I was not performing any sort of cleanup routine to unregister the listeners of the eventmap. The key piece of information to understand when using the RelaxedEventMap is that there is only ONE eventmap shared across all of your mediators (unlike the normal eventmap which each mediator has an individual copy of). The result of this is that if you do not properly clean up after yourself (i.e. removing listeners to the RelaxedEventMap from your mediators upon removal), then the listeners will still exist and will continue to pickup events even after the view has been removed.

After reviewing the notes on using the RelaxedEventMap, I found that there are two ways (technically 3, however I am only covering the two that I find most useful here) of removing your listeners on removal.

You can unregister each individual listener using the unmapRelaxedListener method (similar to using removeEventListener) like so:

Or, you can remove all listeners for this individual mediator by using the unmapListenersFor() method and passing in “this” to provide a reference to the mediator:

Both of of these options should be implemented in the preRemove() method of the mediator so that they will be fired during cleanup (when the mediator/view is removed):

Now for the GOTCHA! When I first implemented the above into my code, I opted for the unMapListenersFor method due to my general laziness. I fired up my application, expecting to now see a single set of events firing; however, nothing changed. I did a bit more digging, and found that it was my laziness that got me into trouble. The unmapListenersFor() method uses the mediator (aka “this”) as the key when unmapping all of the event listeners. Without it, there is no reference to which listeners belong to which mediator. What turned out to be the cause of my problem was the mapping of my listeners, not the unmapping.

When I mapped my listeners to the RelaxedEventMap, I was not passing in any reference to the mediator, and as such, was not establishing any linkage between mediator and event. So when I passed in my mediator to the unMapListenersFor method, there was no reference to it, and thus, the listeners could not be removed.

My initial (lazy) event mapping looked like this:

My updated (correct) mapping looks like this:

Bottom line: don’t be lazy! Make sure to pass in a reference to your mediator. Also, hugs before drugs, you mess with the bull you get the horns, and crack is whack.

One Comment

So, what do you think ?