I am using Backbone.js in my project. I have created a new instance of a view in a render function of another view

render: function (data) {
    var newView = new View();
}

need to call same render function again and again without refreshing the page. if i do so, it creates multiple instances. How do i destroy/hide the previously created instance before creating the new one?

2

There are 2 answers

0
nikoshr On

Store a reference to your view and then destroy it when you create a new instance with view.remove / view.undelegateEvents / custom code to completely detach it:

render: function() {
    if (this.subview)
        this.subview.remove();

    this.subview = new View();
}
0
Arshad Rehmani On

Below is a straightforward approach. I have used it many times.

Assuming you have a global variable declared (say 'globalHandle)

render: function (data) {
    if(globalHandle.newView)
      return globalHandle.newView;

    var newView = new View();
    globalHandle.newView = newView;
}

Also, you can refer to globalHandle.newView from any part of your application to check whether it exists.