Het*_*Joe 11 browser-history backbone.js
我最近通过阅读一本书开始学习Backbonejs.我觉得这个问题有点混乱.这是一个路由器:
define(['views/index', 'views/login'], function(indexView, loginView) {
var SelinkRouter = Backbone.Router.extend({
currentView: null,
routes: {
'home': 'home',
'login': 'login'
},
changeView: function(view) {
if(null != this.currentView)
this.currentView.undelegateEvents();
this.currentView = view;
this.currentView.render();
},
home: function() {
this.changeView(indexView);
},
login: function() {
this.changeView(loginView);
}
});
return new SelinkRouter();
});
Run Code Online (Sandbox Code Playgroud)
这是应用程序的启动方法:
define(['router'], function(router) {
var initialize = function() {
// Require home page from server
$.ajax({
url: '/home', // page url
type: 'GET', // method is get
dataType: 'json', // use json format
success: function() { // success handler
runApplicaton(true);
},
error: function() { // error handler
runApplicaton(false);
}
});
};
var runApplicaton = function(authenticated) {
// Authenticated user move to home page
if(authenticated) window.location.hash='home';
//router.navigate('home', true); -> not work
// Unauthed user move to login page
else window.location.hash='login';
//router.navigate('login', true); -> not work
// Start history
Backbone.history.start();
}
return {
initialize: initialize
};
});
Run Code Online (Sandbox Code Playgroud)
我的问题是关于这一runApplication部分.我读过的这本书的例子就像这样将路由器传递到模块中,但它使用了window.location.hash = "XXX",路由器根本没有被触及.
我认为"导航"方法会使浏览器移动到我指定的页面,但什么也没发生.为什么?
为了最佳实践,在页面(或视图)之间实现移动的最佳方法是什么?
谢谢你的想法.
gri*_*ble 18
您还可以使用静态方法来避免路由器依赖(例如,使用requirejs时).
Backbone.history.navigate(fragment, options)
Run Code Online (Sandbox Code Playgroud)
这样,你只需要:
// Start history
Backbone.history.start();
// Authenticated user move to home page
if(authenticated)
Backbone.history.navigate('home', true);
// Unauthed user move to login page
else
Backbone.history.navigate('login', true);
Run Code Online (Sandbox Code Playgroud)
Ako*_*s K 12
根据文档,如果您还想调用属于特定路由的函数,则需要传递选项trigger: true:
每当您在应用程序中找到要保存为URL的点时,请调用导航以更新URL.如果您还想调用路由功能,请将trigger选项设置为true.要更新URL而不在浏览器的历史记录中创建条目,请将replace选项设置为true.
您的代码应如下所示:
if(authenticated)
router.navigate('home', {trigger: true});
Run Code Online (Sandbox Code Playgroud)
创建路由器后,您还必须致电
Backbone.history.start();
Run Code Online (Sandbox Code Playgroud)
Backbone.history.start([选项])
创建所有路由器并正确设置所有路由后,请调用Backbone.history.start()以开始监视hashchange事件并调度路由.
最后,runApplication逻辑将类似于:
var runApplicaton = function(authenticated) {
var router = new SelinkRouter();
// Start history
Backbone.history.start();
// Authenticated user move to home page
if(authenticated)
router.navigate('home', true);
// Unauthed user move to login page
else
router.navigate('login', true);
}
Run Code Online (Sandbox Code Playgroud)