9

这是我的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 小片段。

4

1 回答 1

14

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

尝试在两次通话后删除您的'*other'路线routes并添加它: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)没有说任何有用的东西。

于 2012-03-07T03:27:12.793 回答