Pattern to manage views in backbone

血红的双手。 提交于 2019-12-02 14:56:08

you are right, there is no build in solution to that (yet).

however it is of course possible to extend backbone to provide this functionality, Derick Bailey has written a blog post about this recently,

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

this is by no means the holy grail, you are free to implement as you wish, but it is a very straight forward approach, for handling zombie views, now you still need to take care of other creatures crawling in your memory, but this is a start with the views at least!

I'm using a custom BaseView, which extends Backbone's remove method:

app.BaseView = Backbone.View.extend({

    views: [], // array to keep a ref of child-views for proper disposal later on

    remove: function() {

        // dispose any sub-views
        _.each(this.views || [], function(view) {
            view.remove();
        });

        // if the inheriting class defines a custom on-remove method, call it!
        _.isFunction(this.onRemove) && this.onRemove();

        // unbind all events from this view
        this.off();

        // finally, call Backbone's default remove method to
        // remove the view from the DOM
        Backbone.View.prototype.remove.call(this);
    }
}

There's still a catch: models and collections need to be disposed by hand, because you don't know if it's used by other views too.

Seems Marionette finally has the functionality I'm looking for.

I post my solution to manage view at https://github.com/thomasdao/Backbone-View-Manager.

The view manager will always cleanup existing view before create a new view. Now I will initialize a new view by:

newView = VM.createView("newView", function(){
             return new View();
          };

If I want to reuse a view instead of creating a new one, I can use

newView = VM.reuseView("newView", function() {
              return new View();
          }

The different between VM.reuseView and VM.createView is that, reuseView will look for existing view with name "newView", if found it will return to you. Else, it will execute the callback function and cache result. VM.createView will always execute the callback function and cleanup existing view for you. Hence you may like to use VM.createView if the views is dynamic and frequently change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!