Ember.js - 动态添加组件到视图

时间:2013-12-27 07:53:51

标签: jquery ember.js

嗨,谢谢你抽出时间回答我的问题。

我希望能够将<li>元素(实现为Component)动态添加到元素(我可以从View中获取引用)。

我有以下代码:

...
<script type="text/x-handlebars" id="components/team-effort">
  <li>
    <button {{action remove}}>remove</button>
  </li>
</script>
...

<script type="text/x-handlebars" data-template-name="projects">.
    <button {{action "addNewTeamEffort" target="view"}}>Add New Team</button><br />
    <ul id="teameffortul">
       {{team-effort}}
    </ul>  
</script>

App.TeamEffortComponent = Ember.Component.extend({
    didInsertElement: function(){
        console.log('didInsertElement - TeamEffortComponent');
    },
    actions: {
        remove: function(){
            this.remove();
            console.log('removed a component');
        }
    }
});

and finally the view:

    App.ProjectsView = Ember.View.extend({
    templateName: "projects",
    didInsertElement: function(){
        jQuery('.datepicker').datepicker();
    },
    actions: {
        addNewTeamEffort: function(){
            App.TeamEffortComponent.create().appendTo(jQuery('#teameffortul'));
            console.log('added team effort!');
        }
    }
});

每当我点击“添加新团队按钮”时,在视图中调用相应的方法,我收到以下错误:

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

当我有:

addNewTeamEffort: function(){
                jQuery('#teameffortul').append('<li>test</li>');
                console.log('added team effort!');
            }

而不是:

addNewTeamEffort: function(){
                App.TeamEffortComponent.create().appendTo(jQuery('#teameffortul'));
                console.log('added team effort!');
            }

它按预期工作,<li>元素附加到<ul>。你能发现我的错误吗?

1 个答案:

答案 0 :(得分:2)

我通过明确添加templateName来实现它:

App.TeamEffortComponent = Ember.Component.extend({
    templateName: "components/team-effort",
    ...

您可以看到有效的JSBin here

希望这有帮助。