简体   繁体   English

Ember.js:“ init”挂钩在ObjectController上被调用了两次

[英]Ember.js: 'init' hook being called twice on ObjectController

I was fiddling around with Ember and I came across something that confused me. 我在和Ember嬉戏,遇到了令我困惑的事情。

I have an ArrayController ( Index ) with an item controller ( Post ). 我有一个带有项目控制器( Post )的ArrayController( Index )。 For the init hook on the Post item controller, I have it send a debug line out to the console. 对于Post项目控制器上的init钩子,我可以将调试行发送到控制台。 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 在JSBin上的代码: http : //emberjs.jsbin.com/momikuto/14/edit

HTML: 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: 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. 如果删除帖子2并仅使用帖子1,则两次获得init for post 1 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. ArrayControl中的Post对象数量似乎与问题无关。


I saw one post on the Ember Github, but it was closed after it was assumed to not be an Ember issue. 我在Ember Github上看到了一个帖子,但是在假定不是Ember问题之后就关闭了。 Any ideas? 有任何想法吗?

You're creating it twice. 您要创建两次。 You have itemController set on your IndexController and you're actually creating the controller in the addPost function. 您已经在IndexController上设置了itemController ,并且实际上是在addPost函数中创建控制器。

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 . Ember将在您pushObject时为您创建itemControler实例,因此您无需手动create

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM