1

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?

Charith Prabhagya
  • 189
  • 1
  • 3
  • 11

1 Answers1

0

You can do something like

if(this.currentView) {
    this.currentView.remove();
}
this.currentView = new AboutView();

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

return Backbone.Router.extend({
  routes: {
    "courses": "viewCourses",
    "about": "viewAbout",
  },
  viewCourses: function () {
    var courseCollection = new Courses();
    courseCollection.fetch()
    .done((response => {
       const courseView = this.renderView(CoursesView, {
           collection: courseCollection
       });
    })
    .fail(this.onError);
  },
  viewAbout: function () {
    const aboutView = this.renderView(AboutView);
  },
  renderView(View, viewOptions) {
    this.currentView && this.currentView.remove();
    this.currentView = new View(viewOptions);
    this.currentView.render();
    return this.currentView;
  }
T J
  • 42,762
  • 13
  • 83
  • 138