Backbone general router vs. separate routing files?

百般思念 提交于 2019-12-08 11:13:07

问题


I found that most tutorials use one big router. For example: https://github.com/thomasdavis/backboneboilerplate/blob/gh-pages/js/router.js

Wouldn't it be better to separate the routes (controllers) into separate files?

If yes how can I combine this with requirejs?


回答1:


I think this is a question of preference. If you're doing a ginormous application with gazillion routes, then dividing your routers up is sensible. For small applications having just one big router is just fine.

If you decide to have multiple routers, make sure you don't have conflicting routes, so there won't be any unexpected behavior or errors.

So with requireJS: I think the best way would be to define each router in it's own file like this

define([blaa, blaa], function(Blaa, Blaa) {

  var SubRouter1 = Backbone.Router.extend({

    // work your routing magic here, remember to make no conflicting routes

  });

  return SubRouter1;
});

When you have all your desired routers set up you can bundle them up in the app.js

define([...,'subrouter1', 'subrouter2', ... , 'subrouterN', ...],
function(..., SubRouter1, SubRouter2, ... , SubRouterN, ...) {

  // work your app magic here

  initialize: function() { // or wherever you start your application
    subrouter1 = new SubRouter1();
    subrouter2 = new SubRouter2();
    ...
    ...
    subrouterN = new SubRouterN();
    Backbone.history.start(); // remember to start the history 
  },

  // maybe work some more magic?
});

I've never done this myself, but I don't see why it wouldn't work if you keep the routes from conflicting. Hopefully this clears stuff for you.




回答2:


check Backbone.js "fat router" design conundrum out : you can find @jakee answer there and some more options



来源:https://stackoverflow.com/questions/11261449/backbone-general-router-vs-separate-routing-files

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