首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Backbone.js -删除所有子视图

问Backbone.js -删除所有子视图
EN

Stack Overflow用户
提问于 2012-03-02 03:42:47
回答 4查看 9.9K关注 0票数 19

我有一个顶级的PageView,只要路由改变,它就会重新渲染自己。我在这个PageView中嵌入了许多嵌套的子视图。如果我要重新呈现PageView,我是需要移除/解除绑定所有嵌套的子视图以及PageView,还是只需要移除/解除绑定PageView?如果我需要移除/解绑所有的子视图,最好的方法是什么?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-03-02 10:02:50

可以,您需要正确移除并解绑它们:

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

要做到这一点,最简单的方法是在父视图中存储子视图数组。然后在父视图上的close方法中,遍历数组并调用子视图上的close方法:

代码语言:javascript
复制
ParentView = Backbone.View.extend({
  initialize: function(){
    this.childViews = [];
  },

  render: {
    for (var i = 0; i < 10; i++){
      var childView = new ChildView();
      // do stuff with the child view
      this.childViews.push(childView);
    }
  },

  close: function(){
    this.remove();
    this.unbind();
    // handle other unbinding needs, here
    _.each(this.childViews, function(childView){
      if (childView.close){
        childView.close();
      }
    })
  }
});

当您准备好移除/替换父视图时,一定要调用父视图上的close方法。这将确保所有的子对象都被正确清理(假设所有的子对象都有自己的close方法)。

票数 35
EN

Stack Overflow用户

发布于 2013-02-07 02:10:00

一个简单且模块化的类,你可能会发现它很有用。

代码语言:javascript
复制
ContainerView = Backbone.View.extend({
  initialize: function() {
    this.children = [];
  },
  remove: function() {
    Backbone.View.prototype.remove.apply(this, arguments);
    this.removeAllChildren();
  },
  removeAllChildren: function() {
    _.each(this.children, function(view) { view.remove(); });
    this.children = [];
  },
  appendAllChildren: function() {
    _.each(this.children, function(view) { this.$el.append(view.render().$el); }, this);
  }
});

用法:

代码语言:javascript
复制
MyView = ContainerView.extend({
  render: function() {
    this.removeAllChildren();
    this.$el.empty();

    // For each child view...
    // this.children.push(new SomeControl(...));

    this.appendAllChildren();
    return this;
  }
});
票数 3
EN

Stack Overflow用户

发布于 2013-01-17 06:23:22

您可以遍历视图的所有属性并查看哪些属性是Backbone.View的实例,而不是保留子视图的数组;您需要确保在父视图中为每个子视图设置一个属性。

在下面的示例中,子视图被设置为父视图的属性。我不确定循环遍历所有属性会对性能造成什么影响,但是,它可能比跟踪子视图的单独数据结构更容易。

示例:

代码语言:javascript
复制
var ContextView = Backbone.View.extend({
    initialize: function() {
      // views render themselves via their initialize methods
      this.titlebar = new TitlebarView({el: $("#titlebar")});       
      this.toolbar = new ToolbarView({el: $("#toolbar")});
      this.content = new ContentView({el: $("#content")});
    },
    removeChildViews: function() {      
        for(var prop in this){
            if (this[prop] instanceof Backbone.View) {
                console.log("This is a view: "+ prop + ' in ' + this[prop]);    
            }
        }
    }, 
    render: function() {
        this.$el.html(this.el);
    }
  });
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9522845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档