Jakob Dam Jensen
Jakob Dam Jensen

Reputation: 434

Preparing views when routing to initial route

I have a question about routing. The thing is, that I have trouble figuring out how to properly instantiate and render views when my app start for the first time on some route.

For example:

If a user accesses the app via the route /?#a/b/c

My app consists of different sections with subsections. This means that for the above route to work I have to render the view for section A before rendering and displaying the view for subsection B and at last render and display the view for subsubsection C.

The thing is, that this results in a bunch of ugly code in the various routing handlers

a: function(){
   A.render();
}
b: function(){
   A.render();
   B.render();
}
c: function(){
   A.render();
   B.render();
   C.render();
}

So I'm thinking that I'm approaching the problem the wrong way.

When introducing other Routers as the app grows this becomes even harder to maintain I would imagine. A solution would be if there were an event being triggered before the callback for a route is called. But I can't find a such in the docs.

So my question is, how are these situations handled properly? Because my solution doesn't scale. Is there a way for a to always fire when visiting a "subroute"?

Upvotes: 1

Views: 284

Answers (1)

timDunham
timDunham

Reputation: 3318

I haven't found a good way to do this but I'll share what I've done and it may or may not apply to your situation. What I wanted to do was have separate routers that respond to portions of the route but backbone doesn't work that way. Backbone will stop when it finds the first route that matches.

What I've done to handle it is to set up a router like this--notice the custom regex to define the route--hopefully it won't make your eyes bleed

initialize:
{
    this.route(/([^\/]*)[\/]?([^\/]*)?[\/]?([^\/]*)?/, "renderViews", this.renderViews);

},
renderViews: function(mainView, subView, subSubView)
{
    //here you can do something clever--mainView, subView and subSubView may or may not 
    // have values but they are the names of the views.  route of "a/b" will pass 
    // ["a", "b", undefined] as your arguments
    if (mainView)
        (new App.Views[mainView]()).render();
    if (subView)
        (new App.Views[subView]()).render();
    if (subSubView)
        (new App.Views[subSubView]()).render();

}

I realize this isn't exactly what you're probably hoping for but it worked well for me in a project.

good luck

Upvotes: 1

Related Questions