【问题标题】:backbone.js application view switching?主干.js 应用程序视图切换?
【发布时间】:2012-09-03 22:33:54
【问题描述】:
我正在使用 Backbone 为我的 RESTful API 编写前端......到目前为止,我真的很喜欢它。学习这个框架仍然非常有趣。然而,我现在被一些事情难住了,至少对我来说,它应该是直截了当的。
我现在有一个(也是唯一的)主应用程序所在的 html 页面,其中列出了一个或多个产品。而且,假设它位于此处:http://localhost/index.html
我希望能够从产品列表视图切换到新产品视图(通过顶部按钮上的点击事件)。而且,据我了解,我需要开始使用路由器进行切换,使用How to switch views using Backbone.js 中描述的模式。
- 为了实现这种行为,我需要进行视图切换吗?
- 这看起来很古怪:
http://localhost/index.html#product/new
而且,由于我使用 [tornado](http://tornadoweb.org) 作为我的 API 和静态内容的 Web 服务器,因此我不能轻松地实现重写规则。我可能会在不久的将来改用 nginx 来处理静态内容,但我还没有。如果我要使用路由器切换视图,例如从 Review 到 Create(CRUD 操作),我如何更改 URL/URI 以查看更多类似的东西
http://localhost/product/new
【问题讨论】:
标签:
view
backbone.js
url-rewriting
switching
【解决方案1】:
为了接收无哈希 url 更改,您的浏览器必须支持 pushstate。如果我没记错的话,如果您的浏览器不支持 pushstate,Backbone 将回退到使用哈希。为了在应用程序中使用 pushstate,您将使用以下内容初始化您的路由器:
Backbone.history.start({pushState: true})
我喜欢@alexanderb 对视图切换的使用。只需确保在更改视图时正确处理它们。否则你会遇到一些难以调试的复杂问题。阅读更多here。
【解决方案2】:
是的,您需要两件事 - Router 和 ApplicationViewManager(一些类,负责更改视图)。
define(function () {
var ViewManager = function () {
return {
show: _showView
};
};
function _showView(view) {
if (this.currentView) {
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$("#app").html(this.currentView.el);
}
return ViewManager;
});
在路由器中,您可以执行以下操作:
// router
var ApplicationRouter = Backbone.Router.extend({
initialize: function () {
this.viewManager = new ViewManager();
},
routes: {
'': 'dashboard',
'configure/sites/:id': 'configure'
},
dashboard: function () {
var app = require('./apps/DashboardApp');
app.run(this.viewManager);
},
configure: function (id) {
var app = require('./apps/ConfigureApp');
app.run(id, this.viewManager);
}
});
一些代码示例,你可以从这个repository获取。