以编程方式向Backbone.Router添加路由?

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"}

我觉得我缺少某些东西,但我无法弄清楚。我开始学习这个强大的js小工具。

1个回答

13

你的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)没有输出任何有用信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接