我有一个视图,它使用第三方库在didInsertElement钩子中渲染其他DOM元素。添加这些新元素后,我需要在其中添加一些子视图,以便它们可以呈现动态数据。
这是我试过的:
App.MyView = Ember.View.extend({
didInsertElement: function() {
create3rdPartyDomElements();
var element = this.$('someSelector');
childView = this.createChildView(App.SomeViewClass, attributesDict);
childView.appendTo(element);
}
});
(jsbin:http://jsbin.com/idoyic/3)
这会按预期呈现我的视图,但是在Ember RC 7中给出了以下断言错误:“你不能附加到现有的Ember.View。请考虑使用Ember.ContainerView。”
我已经尝试过扩展ContainerView,正如here所建议的那样有效,但我无法在特定的DOM选择器中插入子视图。它只是在父视图的开头插入子视图。
有人可以帮帮我吗?非常感谢!
答案 0 :(得分:4)
这就是我创作的方式:
在中间具有主视图(在该情况下为codemirror)的实现。并且可以在顶部或底部添加更多视图。
App.EditorView = Ember.View.extend({
templateName: 'editor-view',
topView: Ember.ContainerView.extend(),
bottomView: Ember.ContainerView.extend(),
CodeMirrorView: Ember.TextArea.extend({
didInsertElement: function() {
this.codeMirror = CodeMirror.fromTextArea(this.get('element'));
}
})
});
模板:
<script type="text/x-handlebars" data-template-name="editor-view">
{{view view.topView viewName="topViewInstance"}}
{{view view.CodeMirrorView}}
{{view view.bottomView viewName="bottomViewInstance"}}
</script>
表示自定义组件的视图:
App.MyComponent = Ember.View.extend({
templateName: 'click-here',
message: null,
click: function() {
alert(this.get('message'));
}
});
实施:
App.MyEditorView = App.EditorView.extend({
didInsertElement: function() {
this._super();
this.get('topViewInstance').pushObject(App.MyComponent.create({ message: "Hello" }));
this.get('bottomViewInstance').pushObject(App.MyComponent.create({ message: "World" }));
}
});
通过这种方式可以创建新实例,或者扩展App.EditorView
并在顶部或底部插入更多视图。由于topView
和bottomView
为Ember.ContainerView
,因此添加的所有视图都将具有绑定,事件和其他余烬功能。
在jsbin中查看它是否有效http://jsbin.com/ucanam/686/edit
答案 1 :(得分:0)
尝试在视图中添加一个属性,如下所示:
App.MyView = Ember.View.extend({
childViewsContainer: Em.ContainerView.create({}),
didInsertElement: function() {
create3rdPartyDomElements();
var element = this.$('someSelector');
childViewsContainer.createChildView(App.SomeViewClass, attributesDict);
childView.appendTo(element);
}
});
然后,您可以访问您的childViewsContainer并随心所欲地执行任何操作
答案 2 :(得分:0)
您可以将子视图渲染到父视图的隐藏div中,然后将它们分离并附加到didInsertElement
hook中的任意DOM元素。
对于相关问题(组件而非视图),另请参阅this question。