Joe Simpson
Joe Simpson

Reputation: 2594

Ember: ContainerView and Child Views binding data not working

I'm trying to use Ember to dynamically create child views in a ContainerView.

The problem is those child views need data bindings to a value from an attribute given to the container view.

Here is a bit of code showing roughly what I'm doing:

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;
            }
        });
    }
});

And this class is referenced like this:

{{view ReferenceCat.EditorView
    modelBinding=model}}

Upvotes: 0

Views: 646

Answers (1)

jpsanchez
jpsanchez

Reputation: 23

In your modelTypeChanges function instead of using a switch statement to create the different types of childViews you need to override the ContainerView's createChildView function (http://emberjs.com/api/classes/Ember.ContainerView.html#method_createChildView). The createChildView function itself will return the instantiated childView and in that overidded function itself you can place your switch statement. So it will look something like this...

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);
}

So make sure when you call your overridden createChildView function to pass it the object you want bounded in the childView as a property of the object you pass as its second parameter...

 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);

Upvotes: 1

Related Questions