我正在跟踪 Organizing Backbone Using Modules tutorial除了自撰写本文以来我不得不进行的一些调整以适应对依赖项的更改之外,我无法在路由匹配时触发我的 .on() 事件。
如果您查看索引路由器,您会看到一个警报和一个 console.log()。页面加载时都不会触发。也没有js错误。
如有任何帮助,我们将不胜感激。
router.js
define([
'jquery',
'underscore',
'backbone',
'views/index',
'views/ideas'
], function($, _, Backbone, IndexView, IdeasView) {
var AppRouter = Backbone.Router.extend({
'': 'index',
'/ideas': 'showIdeas',
'*actions': 'defaultAction'
});
var initialize = function() {
console.log('this works so i know initialize() is being called');
var app_router = new AppRouter;
// not firing
app_router.on('route:index', function() {
alert('hi');
console.log('hi');
// var index_view = new IndexView();
// index_view.render();
});
// not firing
app_router.on('route:showIdeas', function() {
console.log('showIdeas');
var ideas_view = new IdeasView();
});
//not firing
app_router.on('route:defaultAction', function(actions) {
console.log('No route:', actions);
});
if (!Backbone.history.started ) {
Backbone.history.start();
console.log( "Route is " + Backbone.history.fragment );
}
};
return {
initialize: initialize
};
});
最佳答案
确保将实际路由放在路由器定义的路由哈希中:
var AppRouter = Backbone.Router.extend({
routes: {
'': 'index',
'/ideas': 'showIdeas',
'*actions': 'defaultAction'
}
});
我还要补充一点,我更喜欢将路由的回调放在路由器定义中(这只是一种偏好):
var AppRouter = Backbone.Router.extend({
routes: {
'': 'index',
'/ideas': 'showIdeas',
'*actions': 'defaultAction'
},
index: function () {
// function body here
},
showIdeas: function () {
// function body here
},
defaultAction: function () {
// function body here
}
});
这不是必需的,但对我来说它更容易阅读并了解发生了什么。
关于javascript - 无法让 Backbone.js 路由处理程序在匹配的路由上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19307521/