主干:如何导航到一个路由时处理视图/模式? [英] Backbone: How to dispose a view/model when navigating to a route?
问题描述
我创造一个用户创建项目的清单web应用程序,他使用文件夹来分类。现在假设我有两个文件夹是这样的:
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:
- 所有项目(路径:/)
- 衣橱项目(路线:#GET /衣柜/ ID)
当我这些线路之间导航,我要处理在previous路线呈现的模型。如何和我应该在哪里做呢?是否有被触发,当我浏览到一个新的,途径可能是我能执行此操作的事件?
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?
推荐答案
有很多方法可以解决这个,它真的取决于你怎么做的导航。如果您要改变实际联系的路线,或者通过使用 router.navigate()
,您路由器
将派遣一个路线:<路线名称>
事件,你可以听,传递相同的参数处理程序,因为它传递的路由功能
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.
在什么结果是它只需多长时间来建立测试用例code。与骨干示范,我做你的jsfiddle来说明这种方法:的 http://jsfiddle.net/nrabinowitz/ZrgJF/7/
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/
很多,这只是设置code;对于这个问题的重要的部分是路由器:
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
});
这篇关于主干:如何导航到一个路由时处理视图/模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!