【问题标题】:Programmatically adding routes to Backbone.Router?以编程方式将路由添加到 Backbone.Router?
【发布时间】:2012-03-24 14:37:16
【问题描述】:

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

【问题讨论】:

    标签: backbone.js routing backbone-routing


    【解决方案1】:

    您的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对象they're stored inside Backbone.history中:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      • 2016-12-12
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多