0

当我想尝试将一个组件添加到div另一个组件的 DOM 中时出现错误。

未捕获的错误:断言失败:您不能附加到现有的 Ember.View。考虑改用 Ember.ContainerView。

这是我的JSBin

App = Ember.Application.create();

App.MyListComponent= Ember.Component.extend({
  layoutName:'my-list',
  actions:{
  addItem:function(){
   console.log("add item action");
   
 App.MyListItemComponent.create().appendTo("#holder");
  },
  },
});
App.MyListItemComponent= Ember.Component.extend({
  layoutName:'my-list-item',
});
html, body {
  margin: 20px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ember Starter Kit</title>
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://builds.emberjs.com/release/ember-template-compiler.js"></script>
  <script src="http://builds.emberjs.com/release/ember.debug.js"></script>
</head>
<body>

  <script type="text/x-handlebars">
    <h2>Welcome to Ember.js</h2>

    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="index">
    {{my-list}}
  </script>

<script type="text/x-handlebars" id="my-list">
<button {{action "addItem"}}>add item</button>
    This is a holder:
    <div id="holder">
      i am inside holder
    </div>
    
    This is static item:
    {{my-list-item}}
  </script>
  
  <script type="text/x-handlebars" id="my-list-item">
i am a list item
  </script>
  
</body>
</html>

你能看看并告诉我怎么做吗?

非常感谢您

4

1 回答 1

1

我不认为,你的方法是正确的。组件应该独立于添加它的上下文来工作。您可以将任何内容作为参数传递给模板中的组件。我建议根据每次 addItem 单击添加的某种类型的模型来显示组件(在我的示例中,是一个简单的文本)。你为什么不这样尝试:

JS

App = Ember.Application.create();

App.MyListComponent= Ember.Component.extend({
components: Ember.A([]),
layoutName:'my-list',
actions:{
    addItem:function(){
        var components = this.get('components');
        console.log(components);
        components.pushObject ('test'); // or whatever you want: could also be components.pushObject(App.MyListItemComponent.create()); if you want to use it later somehow. 
        this.set('components', components);
        console.log("add item action");
    },
},
});
App.MyListItemComponent= Ember.Component.extend({
layoutName:'my-list-item',
});

html

<script type="text/x-handlebars" id="my-list">
<button {{action "addItem"}}>add item</button>
This is a holder:
<div id="holder">
    i am inside holder {{components.length}}
    {{#each components as |item|}}
        {{my-list-item}}
    {{/each}}

</div>

This is static item:
{{my-list-item}}

于 2015-12-17T17:29:12.357 回答