rpabon
rpabon

Reputation: 1201

Managing views with routers in Backbone.js

I am working in a single page app that has the following layout:

Layout of the app

I am using a Backbone.js router to manage the elements that load on the screen:

var AppRouter = Backbone.Router.extend({
    routes: {
        ""              : "list",
        "content1"      : "content1",
        "content1/cont3": "cont3"
    },

    list: function() {
        var list = new List().render().$el; //view
        $("#List").html(list);
    },

    content1: function(){
        var cont1 = new Content1().render().$el; //view
        $("#Content1").html(cont1);
    },

    content3: function(){
        var cont3 = new Content3().render().$el; //view
        $("#Cont3").html(cont3);
    }        

});

Everytime I click on a list item in #List, #Content1 gets generated, and when I do it on the blocks on #Content1, #Cont3 appears.

The problem I am facing is that if, for some reason, I refresh the page when the adress is localhost/content1, for example; the elements in #List disappear.

I want the content in #List to be always present when loaded, independent on what the url may be, as well as the content in #Content1. Is there a way to achieve this using backbone routers?

Thanks

Upvotes: 5

Views: 2682

Answers (2)

corbacho
corbacho

Reputation: 9052

You don't need to match 1 route <-> 1 View.
I would change the routes to something like this:

"list": "displayContent",
"list/:c1": "displayContent",
"list/:c1/:c3": "displayContent",

So it's only one callback the one who organize what Views are rendered or what not.

displayContent: function(c1,c3) {

Store the content1 variable, and check if has been rendered already or not, etc.

Have a look to this question: How to handle initializing and rendering subviews in Backbone.js?

Or for more complex apps, maybe a layout framework in top of Backbone could help, although I would recommend do your own stuff until you understand how Backbone works.

https://github.com/tbranyen/backbone.layoutmanager
https://github.com/derickbailey/backbone.marionette

Upvotes: 4

Justin wong
Justin wong

Reputation: 638

I think you can try this:

.....
   list: function() {
        var list = new List().render().$el; //view
        $("#List").html(list);
    },

    content1: function(){
        var cont1 = new Content1().render().$el; //view
        $("#Content1").html(cont1);
        //Pseudo code
        if (listisempty){
           list();//If the list is empty, then the initialization list.
        };
    },

.....

Upvotes: 0

Related Questions