Programmatically adding routes to Backbone.Router?

痴心易碎 提交于 2019-12-08 17:07:26

问题


Here is my application-router.js file where i'm creating Backbone.Router object with just only few routes:

var App = App || {};

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

In main javascript file application.js i'd like to programmatically add routes. I've tried with route() function and it doesn't work, routes are not added. It works however passing an object to the "constructor", but that will override already defined routes:

// 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');

In fact console.log(App.Router) shows:

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

I suppose i'm missing something i can't figure out, i'm beginning learning this little piece of powerful javascript.


回答1:


Your router.route calls are working, those calls aren't your problem. When you call route to add a new route, the new route goes at the end of the routing list. In particular, the routes that are added by your route calls go after '*other' and '*other' will match anything so your new routes will be effectively ignored.

Try removing your '*other' route from routes and adding it after your two route() calls:

routes : {
    ''      : 'showDashboard' // Not shown
},

router.route(ExposeTranslation.get('customers.new.route'), 'newCustomer');
router.route('/test/me/again', 'testAgainRoute');
router.route('*other', 'showModalError');

The routes aren't stored in App.Router object, they're stored inside Backbone.history:

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

That's why your console.log(App.Router) doesn't say anything helpful.



来源:https://stackoverflow.com/questions/9595182/programmatically-adding-routes-to-backbone-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!