我最近通過閱讀一本書開始學習Backbonejs。我覺得這個issue.Here有點搞不清是一個路由器:我應該使用哪一個? Backbone.js Router.navigate和window.location.hash
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();
});
,這是一個應用程序的啓動方法:
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
};
});
我的問題是關於runApplication
部分。我讀的這本書的例子就是這樣將路由器傳入模塊,但它使用了window.location.hash = "XXX"
,而路由器根本沒有被觸及。
我認爲「導航」方法會使瀏覽器移動到我指定的頁面,但什麼也沒有發生。爲什麼?
對於最佳實踐,在頁面(或視圖)之間實現移動的最佳方法是什麼?
感謝您的任何想法。
感謝,akoskm。就像你說的那樣,我嘗試在router.navigate()前面移動Backbone.history.start(),它工作正常。所以我必須在導航到某個地方之前開始歷史記錄,對吧? – 2013-04-18 07:23:36
@HetfieldJoe開始監視hashchange事件(導航)是正確的,您必須啓動Backbone.history,請參閱上述文檔中的引用。 – 2013-04-18 07:29:05
響亮而清晰。謝謝,夥計。 – 2013-04-18 07:38:55