Ember.js – Add Components dynamically to a View

Asked By: Anonymous

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?


Solution

Answered By: Anonymous

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.


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen Windows 10 Lisans Office 2019 Mac Satın Al follower kaufen instagram follower kaufen porno