Reputation: 4091
I was fiddling around with Ember and I came across something that confused me.
I have an ArrayController (Index
) with an item controller (Post
). For the init
hook on the Post
item controller, I have it send a debug line out to the console. This debug statement is being sent twice for each post, and I can't figure out why.
Code on JSBin: http://emberjs.jsbin.com/momikuto/14/edit
HTML:
<script type="text/x-handlebars">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
{{each controller itemViewClass="App.PostView"}}
</script>
<script type="text/x-handlebars" data-template-name="post">
POST {{id}}<br />
</script>
JavaScript:
App = Ember.Application.create();
App.IndexController = Ember.ArrayController.extend({
itemController: 'post',
templateName: 'index',
addPost: function (id) {
this.pushObject(App.PostController.create({ id: id }));
}
});
App.PostController = Ember.ObjectController.extend({
debug: function () {
console.log('init for post ' + this.get('id'));
}.on('init')
});
App.IndexView = Ember.View.extend({
didInsertElement: function () {
this.get('controller').addPost(1);
this.get('controller').addPost(2);
}
});
App.PostView = Ember.View.extend({
tagName: 'span',
templateName: 'post'
});
Output:
init for post 1
init for post 1
init for post 2
init for post 2
If I remove post 2 and only use post 1, I just get init for post 1
twice. If I add a post, I get all three of them twice. The number of Post objects in the ArrayControl does not seem to have anything to do with the problem.
I saw one post on the Ember Github, but it was closed after it was assumed to not be an Ember issue. Any ideas?
Upvotes: 1
Views: 1212
Reputation: 2409
You're creating it twice. You have itemController
set on your IndexController
and you're actually creating the controller in the addPost
function.
You shouldn't ever need to create a controller instance yourself, except for some strange edge cases. Ember will create the itemControler
instance for you when you pushObject
so you don't need to manually create
.
Upvotes: 2