Backbone.js : repopulate or recreate the view?

后端 未结 7 1123
灰色年华
灰色年华 2020-11-27 08:49

In my web application, I have a user list in a table on the left, and a user detail pane on the right. When the admin clicks a user in the table, its details should be displ

相关标签:
7条回答
  • 2020-11-27 09:24

    I always destroy and create views because as my single page app gets bigger and bigger, keeping unused live views in memory just so that I can re-use them would become difficult to maintain.

    Here's a simplified version of a technique that I use to clean-up my Views to avoid memory leaks.

    I first create a BaseView that all of my views inherit from. The basic idea is that my View will keep a reference to all of the events to which it's subscribed to, so that when it's time to dispose the View, all of those bindings will automatically be unbound. Here's an example implementation of my BaseView:

    var BaseView = function (options) {
    
        this.bindings = [];
        Backbone.View.apply(this, [options]);
    };
    
    _.extend(BaseView.prototype, Backbone.View.prototype, {
    
        bindTo: function (model, ev, callback) {
    
            model.bind(ev, callback, this);
            this.bindings.push({ model: model, ev: ev, callback: callback });
        },
    
        unbindFromAll: function () {
            _.each(this.bindings, function (binding) {
                binding.model.unbind(binding.ev, binding.callback);
            });
            this.bindings = [];
        },
    
        dispose: function () {
            this.unbindFromAll(); // Will unbind all events this view has bound to
            this.unbind();        // This will unbind all listeners to events from 
                                  // this view. This is probably not necessary 
                                  // because this view will be garbage collected.
            this.remove(); // Uses the default Backbone.View.remove() method which
                           // removes this.el from the DOM and removes DOM events.
        }
    
    });
    
    BaseView.extend = Backbone.View.extend;
    

    Whenever a View needs to bind to an event on a model or collection, I would use the bindTo method. For example:

    var SampleView = BaseView.extend({
    
        initialize: function(){
            this.bindTo(this.model, 'change', this.render);
            this.bindTo(this.collection, 'reset', this.doSomething);
        }
    });
    

    Whenever I remove a view, I just call the dispose method which will clean everything up automatically:

    var sampleView = new SampleView({model: some_model, collection: some_collection});
    sampleView.dispose();
    

    I shared this technique with the folks who are writing the "Backbone.js on Rails" ebook and I believe this is the technique that they've adopted for the book.

    Update: 2014-03-24

    As of Backone 0.9.9, listenTo and stopListening were added to Events using the same bindTo and unbindFromAll techniques shown above. Also, View.remove calls stopListening automatically, so binding and unbinding is as easy as this now:

    var SampleView = BaseView.extend({
    
        initialize: function(){
            this.listenTo(this.model, 'change', this.render);
        }
    });
    
    var sampleView = new SampleView({model: some_model});
    sampleView.remove();
    
    0 讨论(0)
  • 2020-11-27 09:28

    One alternative is to bind, as opposed to creating a series of new views and then unbinding those views. You'd accomplish this doing something like:

    window.User = Backbone.Model.extend({
    });
    
    window.MyViewModel = Backbone.Model.extend({
    });
    
    window.myView = Backbone.View.extend({
        initialize: function(){
            this.model.on('change', this.alert, this); 
        },
        alert: function(){
            alert("changed"); 
        }
    }); 
    

    You'd set the model of myView to myViewModel, which would be set to a User model. This way, if you set myViewModel to another user (i.e., changing its attributes) then it could trigger a render function in the view with the new attributes.

    One problem is that this breaks the link to the original model. You could get around this by either using a collection object, or by setting the user model as an attribute of the viewmodel. Then, this would be accessible in the view as myview.model.get("model").

    0 讨论(0)
  • 2020-11-27 09:32

    I think most people start with Backbone will create the view as in your code:

    var view = new UserDetailView({model:this.model});
    

    This code creates zombie view, because we might constantly create new view without cleanup existing view. However it's not convenient to call view.dispose() for all Backbone Views in your app (especially if we create views in for loop)

    I think the best timing to put cleanup code is before creating new view. My solution is to create a helper to do this cleanup:

    window.VM = window.VM || {};
    VM.views = VM.views || {};
    VM.createView = function(name, callback) {
        if (typeof VM.views[name] !== 'undefined') {
            // Cleanup view
            // Remove all of the view's delegated events
            VM.views[name].undelegateEvents();
            // Remove view from the DOM
            VM.views[name].remove();
            // Removes all callbacks on view
            VM.views[name].off();
    
            if (typeof VM.views[name].close === 'function') {
                VM.views[name].close();
            }
        }
        VM.views[name] = callback();
        return VM.views[name];
    }
    
    VM.reuseView = function(name, callback) {
        if (typeof VM.views[name] !== 'undefined') {
            return VM.views[name];
        }
    
        VM.views[name] = callback();
        return VM.views[name];
    }
    

    Using VM to create your view will help cleanup any existing view without having to call view.dispose(). You can do a small modification to your code from

    var view = new UserDetailView({model:this.model});
    

    to

    var view = VM.createView("unique_view_name", function() {
                    return new UserDetailView({model:this.model});
               });
    

    So it is up to you if you want to reuse view instead of constantly creating it, as long as the view is clean, you don't need to worry. Just change createView to reuseView:

    var view = VM.reuseView("unique_view_name", function() {
                    return new UserDetailView({model:this.model});
               });
    

    Detailed code and attribution is posted at https://github.com/thomasdao/Backbone-View-Manager

    0 讨论(0)
  • 2020-11-27 09:35

    I blogged about this recently, and showed several things that I do in my apps to handle these scenarios:

    http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

    0 讨论(0)
  • 2020-11-27 09:35

    Use this method for clearing the child views and current views from memory.

    //FIRST EXTEND THE BACKBONE VIEW....
    //Extending the backbone view...
    Backbone.View.prototype.destroy_view = function()
    { 
       //for doing something before closing.....
       if (this.beforeClose) {
           this.beforeClose();
       }
       //For destroying the related child views...
       if (this.destroyChild)
       {
           this.destroyChild();
       }
       this.undelegateEvents();
       $(this.el).removeData().unbind(); 
      //Remove view from DOM
      this.remove();  
      Backbone.View.prototype.remove.call(this);
     }
    
    
    
    //Function for destroying the child views...
    Backbone.View.prototype.destroyChild  = function(){
       console.info("Closing the child views...");
       //Remember to push the child views of a parent view using this.childViews
       if(this.childViews){
          var len = this.childViews.length;
          for(var i=0; i<len; i++){
             this.childViews[i].destroy_view();
          }
       }//End of if statement
    } //End of destroyChild function
    
    
    //Now extending the Router ..
    var Test_Routers = Backbone.Router.extend({
    
       //Always call this function before calling a route call function...
       closePreviousViews: function() {
           console.log("Closing the pervious in memory views...");
           if (this.currentView)
               this.currentView.destroy_view();
       },
    
       routes:{
           "test"    :  "testRoute"
       },
    
       testRoute: function(){
           //Always call this method before calling the route..
           this.closePreviousViews();
           .....
       }
    
    
       //Now calling the views...
       $(document).ready(function(e) {
          var Router = new Test_Routers();
          Backbone.history.start({root: "/"}); 
       });
    
    
      //Now showing how to push child views in parent views and setting of current views...
      var Test_View = Backbone.View.extend({
           initialize:function(){
              //Now setting the current view..
              Router.currentView = this;
             //If your views contains child views then first initialize...
             this.childViews = [];
             //Now push any child views you create in this parent view. 
             //It will automatically get deleted
             //this.childViews.push(childView);
           }
      });
    
    0 讨论(0)
  • 2020-11-27 09:38

    To fix events binding multiple times,

    $("#my_app_container").unbind()
    //Instantiate your views here
    

    Using the above line before instantiating the new Views from route, solved the issue I had with zombie views.

    0 讨论(0)
提交回复
热议问题