Zac*_*ris 6 swap exchange-server view switch-statement backbone.js
我正在为backbone.js中的联系人管理器实现查看/编辑视图.Web建议使用名为ContactView和ContactEdit的子视图创建一个Contact类.问题是,这些需要在DOM中占用相同的el,因此我无法将子项嵌套在父级中.那是因为从外面看,我希望父视图只能引用联系人,就好像这些孩子是私人的一样.我试过这个,它第一次渲染()时工作:
initialize: function() {
this.view[0] = new CL.Views.ContactView({model: this.model, el: this.el});
this.view[1] = new CL.Views.ContactEdit({model: this.model, el: this.el});
},
render: function() {
this.view[0].render();
return this;
}
Run Code Online (Sandbox Code Playgroud)
但后来我无法交换意见.我尝试了this.view [0] .remove()以及我能想到的一切,但是无法让浏览和编辑视图使用相同的el互相交换.
我认为这意味着在一个视图中有两个模板并且只是交换它们会更好,这些模板已经基本上可以工作了.我认为它是backbone.js不能很好地处理DOM中同一级别的视图的继承.
我宁愿避免使用backbone.js扩展,但是要遵循它们实现的任何模式.我正在尝试以"正确"的方式执行此操作,因为查看/编辑是我们的应用程序中的表单的常见模式.
PS另一种说明这个问题的方法是,如果没有包含它们的父视图,如何隐藏视图并将其替换为backbone.js中的另一个视图?
提前感谢您提供的任何帮助.
我认为您的问题源于您的父视图与子视图共享相同的元素。当您渲染ContactView或ContactEdit视图时,它会替换 DOM 元素,而当您remove呈现子视图时,它(根据定义)也会删除父视图元素,因为它们是相同的元素。
相反,您应该组合父视图,以便将子视图渲染到容器元素中。就像是
<!-- .contact-container is the parent view el -->
<section class="contact-container">
</section>
Run Code Online (Sandbox Code Playgroud)
然后将子视图渲染到容器中:
initialize: function() {
//don't give the views an element, let them render into the detached
//element generated by Backbone
this.view[0] = new CL.Views.ContactView({model: this.model});
this.view[1] = new CL.Views.ContactEdit({model: this.model});
this.currentViewIndex = 0;
},
render: function() {
//replace the contents with the new view
this.view[this.currentViewIndex].render();
this.$el.html(this.view.el);
return this;
},
swap: function() {
var i = this.currentViewIndex;
this.view[i].remove();
//toggle current view between 0 and 1
this.currentViewIndex = i === 0 ? 1: 0;
this.render();
}
Run Code Online (Sandbox Code Playgroud)
然后你得到
<!-- .contact-container is the parent view el -->
<section class="contact-container">
<div><!-- your child element --></div>
</section>
Run Code Online (Sandbox Code Playgroud)