How to setup multiple routers and controllers in Backbone.Marionette
Asked Answered
C

1

7

As my application grows I feel the need for a more structured router/controller setup. The Marionette docs mention the following:

It is recommended that you divide your controller objects into smaller pieces of related functionality and have multiple routers / controllers, instead of just one giant router and controller.

It would be great if there would be an example for this kind of structure. Suppose I have a website consisting of three sections; People, Media and Articles. Ideally I would like to have routers/controllers for each section. Something like this:

App
  -- AppRouter
       -- AppController
            -- AppLayout
            -- PeopleRouter
               -- PeopleController
                  -- PeopleLayout
            -- MediaRouter
               -- MediaController
                  -- MediaLayout
            -- ArticleRouter
               -- ArticleController
                  -- ArticleLayout

What's very unclear for me is the way how I can let a route ("/people/detail/1") be handled by another router than the AppRouter. It seems that I have to create modules for every section, but does this work nicely with RequireJS? It seems a bit weird to use two different kinds of modules...

It would be great if someone could point me in the right direction, all the examples I found online are a bit confusing to me.

Condominium answered 5/11, 2013 at 9:30 Comment(1)
I had the same confusion you did because what's not explicitly stated is that you can (and should) have more than one AppRouter. Marionette Modules are a way to manage namespace and hide data/functions. I'm still trying to work all this out but I think a better directory structure would be as shown in the code for David Sulc's books: github.com/davidsulc/marionette-gentle-introduction/tree/master/… Each app in the apps directory has its own AppRouter.Rhythmist
P
5

Take a look at the example application developed in my Marionette book.

You can see 2 router files:

If you want to learn more about the routing approach used in the book, there's a free chapter on the subject in the sample. Although it doesn't explain the various router files, it explains the idea of separating app state management from URL management; which might be of interest to you.

Hope this helps !

Pyrotechnic answered 5/11, 2013 at 9:35 Comment(1)
It makes no sense that calling navigate doesn't call the controller method. What is the point in defining a route with a method if its doesn't call it itself? In your example I can't see what the difference would be if you just omitted the Router instance.Chapland

© 2022 - 2024 — McMap. All rights reserved.