0

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?

4

2 回答 2

2

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.

于 2012-06-29T12:28:57.217 回答
0

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

于 2013-11-13T08:53:58.490 回答