Necessary to clean up all event handlers?

1,980 views
Skip to first unread message

KeeganWatkins

unread,
Jul 18, 2010, 12:23:15 PM7/18/10
to nodejs
I'm wondering how important it is to cleanup event handlers bound to
EventEmitter instances... coming from a web-based ECMA background
(Javascript in the browser, ActionScript 3 for the flash platform),
I've grown to be *extremely* conscious about making sure that all
bound handlers are cleaned up. In those realms, I generally unbind
every handler inside the handler, unless the event is going to be used
again, in which case I tend to write widgets with a destroy() method
that removes all event listeners.

Would nodejs best practices follow the same paradigm? Are there memory
management/performance issues with leaving bound handlers, say inside
a closure?

KeeganWatkins

unread,
Jul 18, 2010, 12:23:14 PM7/18/10
to nodejs

Isaac Schlueter

unread,
Jul 18, 2010, 3:54:32 PM7/18/10
to nod...@googlegroups.com
When the event emitter is garbage collected, its bound listeners go
away as well (if the event emitter itself was the only thing aware of
them.) So, if it's a short-lived emitter, there's no need to add a
.destroy method or manually clean up listeners. That's just extra
work that will slow down your app, and v8 will do it for you.

If you need to keep the emitter around for a while, and want to bind a
handler for a single use, then this pattern works well:

emitter.on("event", function runonce (er, data) {
emitter.removeListener("event", runonce)
// dosomething
})

Being inside a closure doesn't really affect the story much. Since
node runs on v8, and not an outdated ancient version of jscript, you
don't have to worry about circular references any more ;)
Mark-and-sweep does a fine job of reclaiming unreachable objects.

--i

Tom

unread,
Jul 18, 2010, 3:58:23 PM7/18/10
to nod...@googlegroups.com
What Isaac said.

I had questions about this too earlier, I think it should be added to the documentation.

- Tom

2010/7/18 Isaac Schlueter <i...@izs.me>

--
You received this message because you are subscribed to the Google Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com.
To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.


KeeganWatkins

unread,
Jul 19, 2010, 11:09:03 AM7/19/10
to nodejs
just what i was hoping to hear, thanks!
> > nodejs+un...@googlegroups.com<nodejs%2Bunsu...@googlegroups.com>
> > .
Reply all
Reply to author
Forward
0 new messages