首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Backbone.js中呈现和附加子视图

如何在Backbone.js中呈现和附加子视图
EN

Stack Overflow用户
提问于 2012-02-14 12:00:32
回答 10查看 72.7K关注 0票数 133

我有一个嵌套的视图设置,它可以深入到我的应用程序中。有一堆方法我可以想到初始化,渲染和附加子视图,但我想知道常见的做法是什么。

下面是我想到的几个

initialize : function () {

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template());

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

的优点:你不必担心通过追加来维护正确的DOM顺序。视图是在早期初始化的,所以在渲染函数中没有那么多事情要一次完成。

缺点:您被迫重新委托costly (),这可能很昂贵?父视图的渲染函数被需要进行的所有子视图渲染弄得乱七八糟?您不能设置元素的tagName,因此模板需要维护正确的tagNames。

另一种方式:

initialize : function () {

},

render : function () {

    this.$el.empty();

    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});

    this.$el.append(this.subView1.render().el, this.subView2.render().el);
}

优点:你不必重新委托事件。您不需要只包含空占位符的模板,并且您的tagName将重新由视图定义。

缺点:现在你必须确保以正确的顺序追加内容。父视图的渲染仍然受到子视图渲染的影响。

使用onRender事件:

initialize : function () {
    this.on('render', this.onRender);
    this.subView1 = new Subview({options});
    this.subView2 = new Subview({options});
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {

    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

优点:子视图逻辑现在从视图的render()方法中分离出来。

使用onRender事件:

initialize : function () {
    this.on('render', this.onRender);
},

render : function () {

    this.$el.html(this.template);

    //other stuff

    return this.trigger('render');
},

onRender : function () {
    this.subView1 = new Subview();
    this.subView2 = new Subview();
    this.subView1.setElement('.some-el').render();
    this.subView2.setElement('.some-el').render();
}

我在所有这些示例中混合和匹配了一堆不同的实践(很抱歉),但是您会保留或添加哪些实践呢?还有什么是你不会做的?

实践总结:

  • 实例化initializerender
  • Perform中的子视图render中或onRender
  • Use setElementappend/appendTo

中的所有子视图呈现逻辑

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9271507

复制
相关文章

相似问题

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