0
votes

I have a UserPanel view, which uses a UserModel as its model. In the template for the UserPanel, I have a conditional that checks whether or not the model is undefined. If the model exists, it displays user information. If it doesn't, it displays the "registration" form.

On the user information part of the UserPanel, I have what's essentially an "unregister" button. A user clicks it, and the user information is deleted. The UserPanel responds by re-rendering, allowing them to register a different UserModel.

Common sense tells me to call this.model.destroy. When I use this method, my model is deleted from my data store, but the object still exists in this.model. When the view responds to the model update (by calling render), it still thinks it has a valid model, with all its data and the like. I can call delete on this.model, but that doesn't trigger any events. I can't trigger the event before I delete, because then the view updates before I can delete the model. I have setup the view to respond to model deletions with a method that simply uses delete on the model, then calls render. This works, but bothers me on a conceptual level, since those methods are for handling view updates and not more model manipulation.

In general, what's the proper way to explicitly dispose of a model that is not stored by a collection?

EDIT: I am using Backbone.localStorage as my data store. This might have something to do with it.

2
some actual code would be niceMulan

2 Answers

0
votes
this.model.destroy();

and then on the destroy event

this.model = null;
0
votes

Instead of binding to the destroy event I would use the success callback of the model.destroy like so:

this.model.destroy({ success: _.bind(this.onModelDestroySuccess, this) });

Then rename your modelDestroyedView to onModelDestroySuccess:

onModelDestroySuccess: function () {
  delete this.model;
  this.render();
},

I would also define a cleanupModelEvents method that cleans up your event bindings to the model:

cleanupModelEvents: function() {
  this.stopListening(this.model);
},

And call that from onModelDestroySuccess:

onModelDestroySucess: function () {
  this.cleanupModelEvents();
  delete this.model;
  this.render();
},

Hope this helps.