I am creating a webapp where user creates an inventory of items and he uses folders to categorize them. Now suppose I have two folders like this:
- All items (route: /)
- Closet items (route: #get/closet/id)
When I navigate between these routes, I want to dispose of the models rendered in the previous route. How and where should I do that? Is there an event which is triggered when I navigate to a new route where may be I can perform this operation?
There are lots of ways to approach this, and it really depends on how you're doing the navigation. If you're changing routes with actual links, or by using router.navigate()
, your router
will dispatch a route:<route name>
event that you can listen to, passing the same arguments to the handler as it passes to the route function.
In what turned out to be a demonstration of just how long it takes to set up test case code with Backbone, I made you a jsFiddle to illustrate this approach: http://jsfiddle.net/nrabinowitz/ZrgJF/7/
A lot of this is just setup code; the important parts for this question are the router:
var MyRouter = Backbone.Router.extend({
routes: {
'view/:id' : 'openView'
},
openView: function(id) {
app.openView(id)
}
});
router = new MyRouter();
And the view, which binds removal to the route:
var MyView = Backbone.View.extend({
initialize: function(opts) {
this.id = opts.id;
router.bind('route:openView', this.dispose, this);
},
// id is the same as the route argument
dispose: function(id) {
if (id != this.id) {
this.remove();
}
}
// etc
});