We are adding components to a ContainerView following this patern:
hbs
{{view Ember.ContainerView viewName="my-menu-container"}}
js
this.get("my-menu-container").pushObject(suggestionBoxViewOrComponent);
By this way, we have a list of components of the same type, managed from javascript component code.
But now, {{view}} is deprecated and hbs throws warnings. What is the best way to replace this pattern by other with more Ember 2 style?
Might want to try using the component helper and an array managed by a parent component. So maybe something like this:
// parent-component/component.js
export default Ember.Component.extend({
children: Ember.computed(function() {
return [];
}),
actions: {
addChild(type) {
// Type is a component name
this.get('children').pushObject(type);
}
}
});
// parent-component/template.hbs
<button {{action 'addChild' 'child-type-a'}}>Add Child A</button>
<button {{action 'addChild' 'child-type-b'}}>Add Child B</button>
{{#each children as |childType|}}
{{component childType}}
{{/each}}
I tried and it works perfectly!
But computed property does not seem necessary. If I replace computed property by:
children: Ember.A()
or simpler:
children: []
Both replacements work. I think these approaches are very clean and respect Ember 2 philosophy. They are a very elegant way to migrate from ContainerView.
Well, if you do that, then you’ll have the same children
array for each of the instances of the parent component.
And old issue, but this is part of Ember’s behavior that is important to be aware of, or you may end up with some weird bugs!:
https://github.com/emberjs/ember.js/issues/462
Some of this was recently discussed here: Programmatically rendering ember components - #8 by jeremytm
TL;DR; Ember.ContainerView
is deprecated. It seems like the way forward is {{each}}
and {{component}}
helpers.
Thanks for the help!
@Spencer_Price, that issue is a very weird thing! I’ll keep it in mind.