以编程方式将路由添加到 Backbone.Router



这是我application-router.js文件,我在其中仅使用少量路由创建Backbone.Router对象:

var App = App || {};
App.Router =  Backbone.Router.extend({
    routes : {
        ''      : 'showDashboard', // Not shown
        '*other': 'showModalError'
    },
    defaultRoute : function(other) { $('#modal404').modal(); }
});

在主 JavaScript 文件中application.js我想以编程方式添加路由。我尝试过 route(( 函数,但它不起作用,没有添加路由。但是,它将对象传递给"构造函数",但它将覆盖已经定义的路由:

// This works and overrides all defined routes in App.Router
var router = new App.Router({ routes : { '/test/me' : 'testRoute' } });
// This is not working
router.route(ExposeTranslation.get('customers.new.route'), 'newCustomer');
router.route('/test/me/again', 'testAgainRoute');

事实上,console.log(App.Router)显示:

routes Object { /test/me="testRoute"}

我想我错过了一些我无法弄清楚的东西,我开始学习这一小段强大的javascript。

您的router.route调用正常工作,这些调用不是您的问题。当您调用 route 添加新路由时,新路由将位于路由列表的末尾。特别是,您的route呼叫添加的路由在'*other'之后,'*other'将匹配任何内容,因此您的新路由将被有效地忽略。

尝试从routes中删除'*other'路由,并在两次route()呼叫后添加它:

routes : {
    ''      : 'showDashboard' // Not shown
},
router.route(ExposeTranslation.get('customers.new.route'), 'newCustomer');
router.route('/test/me/again', 'testAgainRoute');
router.route('*other', 'showModalError');

路由不存储在对象App.Router,它们存储在Backbone.history

route: function(route, name, callback) {
  // ...
  Backbone.history.route(route, _.bind(function(fragment) {
    //...
  }, this));
  return this;
},

这就是为什么你的console.log(App.Router)没有说任何有用的东西。

最新更新