2

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?

Pankaj
  • 21
  • 5

2 Answers2

1

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();
}
nikoshr
  • 32,926
  • 33
  • 91
  • 105
0

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.

ScrapCode
  • 2,109
  • 5
  • 24
  • 44