Backbone.js的:路由嵌套意见 [英] Backbone.js: Routing for nested views

查看:393
本文介绍了Backbone.js的:路由嵌套意见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚以下情形:

让我们说,我有两个观点:一个用于查看项目,一个用于购买。美中不足的是,买视图是查看子视图。

Lets say that I have two views: one for viewing items and one for buying them. The catch is that buying view is a sub view for viewing.

有关路由我有:

var MyRouter = Backbone.Router.extend({
  routes: {
    'item/:id': 'viewRoute',
    'item/:id/buy': 'buyRoute'
  }
});

var router = new MyRouter;

router.on("route:viewRoute", function() {
  // initialize main view
  App.mainview = new ViewItemView();

});

router.on("route:buyRoute", function() {
  // initialize sub view
  App.subview = new BuyItemView();
});

现在,如果用户刷新页面, buyRoute 被触发,但现在没有主视图。什么是处理这个最好的解决办法?

Now if user refreshes the page and buyRoute gets triggered but now there is no main view. What would be best solution to handle this?

推荐答案

您可以只检查的主要观点的存在,并创建/打开它,如果它不存在。

You could just check for the existence of the main view and create/open it if it doesn't already exist.

我通常创建(但不打开),我的应用程序上引导该应用的主要观点,然后某种形式的开/关视图管理器。对于小项目,我只重视我的意见,以一个我的应用程序对象的意见属性,所以他们都在一个地方,views.mainView,views.anotherView访问,等等。

I usually create (but don't open) the major views of my app on booting up the app, and then some kind of view manager for opening/closing. For small projects, I just attach my views to a views property of my app object, so that they are all in one place, accessible as views.mainView, views.anotherView, etc.

我也有两个方法来扩展Backbone.View:打开关闭,不仅追加/删除一个视图/从DOM,但也设置了一个 isOpen会标志上的视图。

I also extend Backbone.View with two methods: open and close that not only appends/removes a view to/from the DOM but also sets an isOpen flag on the view.

通过这个,你可以检查,看是否有需要的视图已经打开,那么如果不打开它,像这样:

With this, you can check to see if a needed view is already open, then open it if not, like so:

if (!app.views.mainView.isOpen) {
    // 
}

这是可选的除了是创建你的应用程序称为 clearViews 扫清任何打开的看法,也许传递作为参数的意见姓名的异常的方法 clearViews 。所以,如果您有没有想清楚了一些路线导航栏一看,你可以叫 app.clearViews('topNav')和意见以外的所有视图.topNav将得到休息。

An optional addition would be to create a method on your app called clearViews that clears any open views, perhaps with the exception of names of views passed in as a parameter to clearViews. So if you have a navbar view that you don't want to clear out on some routes, you can just call app.clearViews('topNav') and all views except views.topNav will get closed.

看看这个主旨为code表示这一切: https://gist.github.com / 4597606

check out this gist for the code for all of this: https://gist.github.com/4597606

这篇关于Backbone.js的:路由嵌套意见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆