0

我正在尝试使用 Ember 在 ContainerView 中动态创建子视图。

问题是那些子视图需要数据绑定到来自容器视图的属性值。

这是一些代码,大致显示了我在做什么:

ReferenceCat.EditorView = Ember.ContainerView.extend({
    init: function(){
        this._super();
        if(this.get('model.type') != undefined){
            this.modelTypeChanges();
        }
    },
    modelTypeChanges : function(){
        // 1st step: Remove all children of my view
        this.removeAllChildren();

        var model = this.get('model');

        // 2nd step is to run through all of the type information
        //          generating the views that we need to actually
        //          fill in this reference
        var tI = model.get('typeInfo');

        var self = this;
        tI.forEach(function(field){
            // Now we have a field
            switch(field.type){
                case "string":
                    // add new child view here with data binding to data.<field.name>
                break;
            }
        });
    }
});

这个类是这样引用的:

{{view ReferenceCat.EditorView
    modelBinding=model}}
4

1 回答 1

1

在您的modelTypeChanges函数中,而不是使用 switch 语句来创建不同类型的子视图,您需要覆盖 ContainerView 的createChildView函数 ( http://emberjs.com/api/classes/Ember.ContainerView.html#method_createChildView )。该createChildView函数本身将返回实例化的 childView,并且在该覆盖函数本身中,您可以放置​​您的 switch 语句。所以它看起来像这样......

createChildView: function(view, attrs) {
  switch(attr.type) {
    case "string":
      view = yourview //your view class here, it is overriding the default 
      break;
  }
.....
...
  //Once you place all your case statements above 
  //make sure to call the parents createChildView function.
  //This line is actually creating the view you want with the 
  //properties that are defined in the object attrs
  return this._super(view, attrs);
}

因此,请确保在调用覆盖createChildView函数时将要在 childView 中绑定的对象作为您作为第二个参数传递的对象的属性传递给它...

 var self = this,
     tempviewarray = [];

 tI.forEach(function(field){
   var view = self.createChildView(null, field);
   tempviewarray.push(view);
 });

 // add all the instantiated views to the ContainerView as children views 
 this.pushObjects(tempviewarray);
于 2013-10-18T13:50:20.487 回答