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 に答える