javascript - How do I get rid of model attached to view after using Backbone's model#destroy? -
i'm seeing success callback in debugger chrome dev tools, i'm still seeing model when type in this.model
. know it's destroyed on server side, can explain why it's still attached view? how rid of it?
delete: function () { this.model.destroy({success: function () {console.log("success in destroy");}}); debugger; }
what seeing correct. looking @ the documentation on model.destroy
(or looking the code) can see 2 things:
- http deletes server representation of model
- removes model containing collections
note nothing happens model or objects model may attached to.
we can see behavior simple example:
var foo = new backbone.model({foo: 'bar'}); var foos = new backbone.collection([foo]); var fooview = new backbone.view(); fooview.model = foo; foo.destroy({success: function () { console.log('success'); }}); console.log(foo, foos, fooview);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>
note nothing happens foo
or fooview.model
after executing code, although foos
no longer contains instance of foo
.
removing view.model
if want remove model view can leverage success callback. change view's delete
method (from question) following:
delete: function () { this.model.destroy({success: function () { delete this.model; }.bind(this)}); }
alternatively, since know docs model fire "destroy"
event, can listen event , fire callback deletes our model.