Question

In the initialize function of my backbone View, I created the following listener:

this.listenTo(this.model.get('clusters'), 'add remove', this.saveChanges);

This successfully causes my saveChanges function to be called the first time a model is added/removed from the 'clusters' Collection. There's only one line in that saveChanges function:

this.model.save();

Once that is invoked, adding/removing clusters no longer invokes the "add" or "remove" event. Why would saving the model destroy the listener? Can that be prevented, or is there a way to re-establish the listener?

Or is there something fundamental I'm not understanding about Models and/or Collections...?

Was it helpful?

Solution

Let's break down your code:

You write

this.listenTo(this.model.get('clusters'), 'add remove', this.saveChanges);

Which is equal to

var clusters = this.model.get('clusters');
this.listenTo(clusters, 'add remove', this.saveChanges);

Now I only assume that after you get that event you set() a new clusters object inside your model.

The issue here is that your view still listens to events from that same old clusters object, which is not relevant anymore - your model deals with another object!

Another case could be that Backbone clears your view's event handlers from its model when it's being removed.. Could easily answer for sure if you'd share the whole code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top