I have a problem regarding Backbone JS views. When a Route change is happen it create new views according to the route function. But the previous views also exist. Therefore there are multiple views exists and couldn't perform At the top of each route, I want to remove the current view and then assign it the new view. This is my main.js file
return Backbone.Router.extend({
routes: {
"": "viewHome",
"about": "viewAbout",
"find-courses": "findCourses",
"courses": "viewCourses",
"*other": "defaultRoute"
},
viewCourses: function () {
var courseCollection = new Courses();
var fetchDone = function () {
if(courseView && courseView.remove) courseView.remove();
this.courseView = new CoursesView({
collection: courseCollection
});
this.courseView.render();
};
var options = {
success: _.bind(fetchDone, this),
error: this.onError
};
courseCollection.fetch(options);
},
onError: function () {
alert('Some Error!');
},
viewAbout: function () {
this.aboutView = new AboutView();
this.aboutView.render();
}
Could you please help me to solve this?
You can do something like
In every route.
Of course you can improve it by extracting that into a separate method which accepts new view constructor when the scale increases, something like