emberjs附加工作但引发断言失败错误

时间:2013-12-10 13:26:14

标签: javascript ember.js

我是ember的新手我正在尝试将模板附加到另一个模板,它似乎有效,但它会引发错误,你能解释一下原因吗?

错误:

Assertion failed: You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead

这是 app.js

中的代码
App.NewStickie = Ember.View.extend({
  click: function(evt){
    var stickie = Ember.View.create({
        templateName: 'stickie',
        content: 'write your notes here'
    });
    stickie.appendTo('#stickies');
  }
});

这些是 index.html

的内容
<script type="text/x-handlebars">
    {{#view App.NewStickie}}
      <button type="button" class="btn btn-success">
        New
      </button>
    {{/view}}
    {{outlet}}
  </script>

  <script type="text/x-handlebars" id="index">
    <div id="stickies">
      {{#each item in model}}
        <div class="stickie" contenteditable="true">
          {{#view App.DeleteStickie}}
            <span class="glyphicon glyphicon-trash"></span>
          {{/view}}
          <div contenteditable="true">
            {{item.content}}
          </div>
        </div>
      {{/each}}
    </div>
  </script>

  <script type="text/x-handlebars" data-template-name="stickie">
    <div class="stickie">
      {{#view App.DeleteStickie}}
        <span class="glyphicon glyphicon-trash"></span>
      {{/view}}
      <div contenteditable="true">
        {{view.content}}
      </div>
    </div>
  </script>

2 个答案:

答案 0 :(得分:1)

ember中的每个视图都有一个模板,例如:

<强> foo_view.js

App.FooView = Ember.View.extend({
  templateName: 'foo'
})

foo模板

<script type="text/x-handlebars" data-template-name="index">   
  <div id=myFooView>Foo</div>
</script>

您正试图以这种方式在其他视图中插入视图:

App.BarView.create().appendTo('#myFooView')

这是不允许的。您可以使用{{view}}把手助手来渲染其他类似的视图:

foo模板

<script type="text/x-handlebars" data-template-name="index">   
  <div id=myFooView>
    Foo
    {{view App.BarView}}
  </div>
</script>

但我认为你希望动态地运作。因此,您可以使用ContainerView,如错误消息所述:

App.StickiesView = Ember.ContainerView.extend({
  click: function() {
    var stickie = Ember.View.create({
        templateName: 'stickie',
        content: 'write your notes here'
    });
    this.pushObject(stickie);
  }
})

我在你的代码中看到很多关于click事件的视图,ember鼓励你使用actions,这提供了更多的灵活性,错误/加载处理等等。我认为使用它是一个好主意。< / p>

我希望它有所帮助

答案 1 :(得分:0)

您应该阅读解释ContainerView的{​​{3}}。另外,我认为没有必要创建另一个View来将模板附加到另一个模板。