【发布时间】:2014-06-16 20:21:49
【问题描述】:
我是 BackboneJS、RequireJS、JQuery 应用程序开发的新手。我想使用router.navigate() 更改当前视图。这是路由器配置:
define([
//Libraries to load
"jquery",
"underscore",
"backbone",
"mustache",
//Views to load
"../views/Main",
"../views/Login",
"../views/Dashboard",
"../views/Empty"
], function ($, _, Backbone, Mustache, MainView, LoginView, DashboardView, HomeView) {
//All of the dependencies in the array above become parameters of the function to be managed
'use strict';
var AppRouter = Backbone.Router.extend({
routes: {
// Default
'*actions': 'defaultAction'
},
loadView: function(view){
this.view && (this.view.close ? this.view.close() : this.view.remove());
this.view = view;
this.view.render();
}
});
var initialize = function(){
var app_router = new AppRouter;
app_router.on('route:defaultAction', function (actions) {
switch (actions){
case "login": this.loadView(new LoginView()); break;
case "home": this.loadView(new HomeView()); break;
}
});
// Extend the View class to include a navigation method goTo (source: http://stackoverflow.com/questions/7755344/using-the-backbone-js-router-to-navigate-through-views-modularized-with-require)
Backbone.View.prototype.goTo = function (loc) {
app_router.navigate(loc, true);
};
Backbone.Model.prototype.goTo = function (loc) {
app_router.navigate(loc, true);
};
Backbone.history.start();
};
return {
initialize: initialize
};
});
在 Backbonejs 视图中,我使用以下代码更改/加载视图:
self.goTo("home");
但只更改 URL 中的主题标签。例如:#login 更改为#home,但不加载视图。我必须使用 URL #home 重新加载页面才能加载主视图。
注意:Backbone.history.navigate("viewname", { trigger: true }); 产生相同的结果。更改 URL 但不更改查看路径。
我的路由器代码已应用:
routes: {
'login': 'renderLogin',
'home': 'renderHome',
// Default
'*actions': 'renderDefault'
},
renderDefault: function(){
this.view = new MainView();
this.view.render();
},
renderLogin: function(){
this.view = new LoginView();
this.view.render();
},
renderHome: function(){
this.view = new HomeView();
this.view.render();
}
}
【问题讨论】:
标签: backbone.js backbone-routing