I want to use Backbone.js for some event handling things, but I am not confident about cyclical references & memory management. Let's say I have some static event source called EventStation - so, at the start of the script I say:
var source = new EventSource();
source
is meant to live for the life of page and that's fine. Now, I also have an event consumer:
var EventConsumer = Backbone.Model.extend({
initialize: function(params) {
source.on("some_event",this.onSomeEvent,this);
}
});
function later() {
var consumer = new EventConsumer();
// consumer now gets leaked... (I think)
}
I call later()
at some point - and at the end, I no longer have any access to consumer, except if I go digging around through the internals of source
. I think I need to add some new function to EventConsumer
, like
cleanup: function() {
source.off("some_event",this.onSomeEvent,this);
}
And then call that at the end of later()
.
This seems... not as clean as I would like it. Is there some way to do this better? Would this handle differently if I was using DOM events?