Dragan
Dragan

Reputation: 3743

Ember.js - Add Components dynamically to a View

Hi and thanks for taking the time to answer my question.

I would like to be able to dynamically add <li> elements (which are implemented as a Component), to an element (to which I can get reference from the View).

I have the following code:

...
<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!');
        }
    }
});

whenever I click the "Add new Team button" the appropriate method is called in the View and I get the following error:

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

When I have:

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

instead of:

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

it works as expected, and <li> element is appended to the <ul>. Can you spot what my mistake is?

Upvotes: 0

Views: 2441

Answers (1)

Scott
Scott

Reputation: 21501

I got it working by adding the templateName explicitly like this:

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

You can see a working JSBin here.

Hope this helps.

Upvotes: 2

Related Questions