elanh
elanh

Reputation: 1441

How do I unbind an event handler after the object I bound to is deleted?

I have the following scenario:

I have a model which has one attribute which is a model itself. In my view, I am binding to the child model like this:

this.listenTo(this.model.get("childModel"), "change", this.handleChange);

Now I have a case where the child model can be unset from some controller because of a user action. In that case, I want to unbind the above handler.

In Backbone.js documentation for the function stopListening, it says:

object.stopListening([other], [event], [callback])

Tell an object to stop listening to events. Either call stopListening with no arguments to have the object remove all of its registered callbacks ... or be more precise by telling it to remove just the events it's listening to on a specific object, or a specific event, or just a specific callback.

So when that child model is unset, I tried doing this in my view:

this.stopListening(this.handleChange);

From the doc, I thought this would be valid, but I got an error from Backbone.

So now I'm trying this:

this.stopListening(null, "change", this.handleChange);

This doesn't cause an error, but how can I be sure that it's really working?

Upvotes: 1

Views: 426

Answers (1)

Loamhoof
Loamhoof

Reputation: 8293

The object argument of the stopListening method is necessary if you're passing arguments (that is, as long as you don't want to remove all the listeners). So you'll have to get the model you unset.

What you can do, for example, is making your view listen to your parent model's childModel's changes, so you can remove the listener as soon as it's unset:

this.listenTo(this.model, 'change:childModel', function(m, v, opt) {
  if(opt.unset)
    this.stopListening(m.previous('childModel'), 'change'); //not sure if you need the second argument, think not...
});

Upvotes: 1

Related Questions