Ember:ContainerView和子视图绑定数据不起作用

时间:2013-10-18 08:40:43

标签: data-binding ember.js

我正在尝试使用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}}

1 个答案:

答案 0 :(得分:1)

modelTypeChanges函数中,您需要覆盖ContainerView的createChildView函数(http://emberjs.com/api/classes/Ember.ContainerView.html#method_createChildView),而不是使用switch语句来创建不同类型的childView。 createChildView函数本身将返回实例化的childView,并且在该overidded函数本身中,您可以放置​​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);