I'm looking for the best pattern to switch views using backbone.js
Let's say I have a basic DOM structure like this:
<div id="header">Some fixed content</div>
<div id="mainContainer"></div>
<div id="footer">Some other content</div>
And I have two views "viewOne" and "viewTwo" that I want to show alternatively in the mainContainer.
The router should be something like this:
routes: {
'one': 'pageOne',
'two': 'pageTwo'
},
pageOne: function() {
viewOne.render();
},
pageTwo: function(){
viewTwo.render();
}
Where should I append or remove the view.el to the DOM? What is the best pattern for switching between the views?
I would use a higher level view (attached to #mainContainer) that would be responsible to render its child view(s). From what you describe, your views are too different to consider rendering them with a single view based on some conditions, and I think its always cleaner tohave a hierarchichal tree of views, so that rendering the whole page is basically a call to the top-level view's .render() (which delegates to children).
Your maincontainer-level view could expose two functions, say renderPageOne and renderPageTwo, and that's all the router has to know. Inside these functions, you can keep track of the child view to render, and call this.render() which clears the current content (using jQuery's .empty() on the maincontainer el), and inserts the correct child view's top element (the .el).
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