Skip to content

Instantly share code, notes, and snippets.

@jasonmit
Created April 20, 2014 19:58
Show Gist options
  • Save jasonmit/11123666 to your computer and use it in GitHub Desktop.
Save jasonmit/11123666 to your computer and use it in GitHub Desktop.
Ember: Component that creates child components http://jsfiddle.net/NQKvy/910/
<style>
h1 { font-size: 1.6em; padding-bottom: 10px; }
h2 { font-size: 1.4em; }
ul { padding: 15px; font-size: 1.4em; color: green; }
.parent-component,
.child-component { display: block; }
</style>
<script type="text/x-handlebars" data-template-name="application">
<h1>ember-latest jsfiddle</h1>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="components/parent-foo">
{{yield}}
{{view view.viewContainer}}
</script>
<script type="text/x-handlebars" data-template-name="components/child-foo">
<div>{{content.lastName}}, {{content.firstName}}</div>
</script>
<script type="text/x-handlebars" data-template-name="index">
<h2>Index Content:</h2>
{{#parent-foo content=this}}
{{!-- you can manually add content but
child-foo components will be created
for every object in parent-foo's content --}}
{{child-foo content=jason}}
{{/parent-foo}}
</script>
<script type="text/javascript">
App = Ember.Application.create({});
App.IndexRoute = Ember.Route.extend({
model: function(){
return [
{firstName: 'Kris', lastName: 'Selden'},
{firstName: 'Luke', lastName: 'Melia'},
{firstName: 'Formerly Alex', lastName: 'Matchneer'}
];
}
});
App.IndexController = Ember.ArrayController.extend({
jason: { firstName: 'Jason', lastName: 'Mitchell' }
});
App.ParentFooComponent = Ember.Component.extend({
content: [],
tagName: 'parent-component',
init: function() {
this._super.apply(this, arguments);
this.viewContainer = Ember.ContainerView.create({});
},
onContentChanged: function() {
Ember.run.scheduleOnce('afterRender', this, function() {
var klass = this.container.lookupFactory('component:child-foo'),
viewContainer = this.get('viewContainer'),
contents = this.get('content');
views = [];
contents.forEach(function(content) {
views.pushObject(klass.create({
target: viewContainer,
content: content,
template: this.container.lookup('template:components/child-foo')
}));
}, this);
viewContainer.setObjects(views);
});
}.observes('content', 'content.[]').on('init')
});
App.ChildFooComponent = Ember.Component.extend({
tagName: 'child-component'
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment