I am working in a single page app that has the following layout:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With