emberjs/ember.js — Issue #461: Swapping Out Child Views Dynamically
Author: ghempton
Created: 2012-01-29 20:57:02+00:00
State: open

I am trying to grapple with the best way to swap out child views dynamically. For instance, consider the following template corresponding to a view:

```

{{header}}

```

I want to be able to append a view to the `.content` div at runtime. I could do something like the following:

```
childView.appendTo('.content')
parentView.get('childViews').pushObject(childView)
```

The problem with the above is that the parentView would have to be in the `inDOM` state for the appendTo to work. I could observe the parent's state and call the code then but that feels hackish.

Alternatively, I could modify the template to something like the following:

```

{{header}}

{{view Em.ContainerView contentBinding="contentViews"}}

```

Then update the contentViews property of the parent when I want to swap out the child view, but this also feels overly complext for swapping out a single view.

After looking at #417, however, I feel the urge to write something like the following

```

{{header}}

{{yield}}

```

Then at runtime do something like the following:

```
// remove existing child
parentView.set('yieldContent', function() { childView.appendTo('parentView'); });
parentView.rerender()
```

A variation of the above logic actually works if the parentView is still in the buffer, but fails for obvious reasons when it is inDom.

Does anyone have some general advice/best practice for this situation? I feel like I'm missing something that would truly accomodate this situation.