How To Switch View Using Router In Backbone.js
I faced the problem that view switches with router. My application is written with Backbone.js. It has 2 views, ApplicationView and ApplicationSubView. Originally, I thought that i
Solution 1:
While I can't really understand the question's description, I can see a lot of improvements that needs to be done so I've made a complete refactor of your code.
Routing is just handling changes in the URL, so you can use anchor tags directly, without explicit events and navigate
calls.
This is all you'd need to trigger the routes.
<body><ulclass="pills"><li><ahref="#/">Home</a></li><li><ahref="#/about">About</a></li><li><ahref="#/contact">Contact</a></li></ul><divid="content"></div></body>
See the <div id="content"></div>
? This is the content div and this is where the other pages will go. We'll manage that using a "layout" view:
var app = app || {};
(function() {
'use strict';
var views = app.view = app.view || {};
views.Application = Backbone.View.extend({
initialize: function() {
// caching the jQuery object on initthis.$content = this.$('#content');
},
setContent: function(view) {
var content = this.content;
if (content) content.remove();
content = this.content = view;
this.$content.html(content.render().el);
},
});
// make a view for each sub-page
views.Home = Backbone.View.extend({ /* ... */ });
views.About = Backbone.View.extend({ /* ... */ });
views.Contact = Backbone.View.extend({ /* ... */ });
})();
Then, you need to define a router that handles these routes.
var app = app || {};
(function() {
'use strict';
var views = app.view = app.view || {};
app.Router = Backbone.Router.extend({
routes: {
'about': 'aboutRoute',
'contact': 'contactRoute',
// put the catch-all last'*home': 'homeRoute',
},
initialize: function() {
// create the layout once herethis.layout = new views.Application({
el: 'body',
});
},
homeRoute: function() {
var view = new views.Home();
this.layout.setContent(view);
},
aboutRoute: function() {
var view = new views.About();
this.layout.setContent(view);
},
contactRoute: function() {
var view = new views.Contact();
this.layout.setContent(view);
}
});
})();
And to use it when the document is ready:
$(function() {
var router = new app.Router();
Backbone.history.start();
});
Post a Comment for "How To Switch View Using Router In Backbone.js"