Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emberjs-2.0 dynamically add more component on click

I have component called display-me. I can add multiple of that same component to thesame template as shown in the jsfiddle by adding multiple calls to that component like this:

  <script type="text/x-handlebars" data-template-name="index">
     {{display-me  action='add'}}
     {{display-me  action='add'}}
  </script>

However, what I desire, is a situation where I can click a button to add the second entry for the component instead of adding it manually as above because I want use to click and add as many as that want.

I have added this action to my index route but it doesn't work:

 App.IndexRoute = Ember.Route.extend({
    actions: {
      add: function(){   

        var comp = App.__container__.lookup("component:display-me");

        //var comp = App.DisplayMeComponent.create();

        //comp.appendTo(".test");
        //comp.appendTo('#input'); 

        Ember.$(".test").append($('<div> {{display-me  action="add"}} </div>'));

      }
    }
  });

Here is the complete jsfiddle

like image 917
brg Avatar asked Jan 08 '23 23:01

brg


1 Answers

You need an each loop in your template to produce multiple inputs.

For the each loop to iterate through something, create a range: an array with as much elements as the desired number of inputs:

http://emberjs.jsbin.com/defapo/2/edit?html,js,output

But this makes little sense as all your inputs will bind to the same value.

In order to have different values, create and populate an array of values:

names: ['James'],

actions: {
  add: function() {
    this.get('names').pushObject('John Doe');
  }
}
{{#each names key="@index" as |name|}}
  <p>  {{input value=name}} </p>
{{/each}}

That's better, but in Ember you'll have a hard time manipulating raw strings. One example is that you need this strange key="@index" thingie.

Instead of raw stings, operate objects:

  people: [ Ember.Object.create({name: 'James'}) ],

  actions: {
    add: function(){   
       this
         .get('people')
         .pushObject(Ember.Object.create({name: 'John Doe'}));
    }
  }
{{#each people as |person|}}
  <p>  {{input value=person.name}} </p>
{{/each}}

Demo: http://emberjs.jsbin.com/defapo/3/edit?html,js,output

The next step for improvement is to use Ember Data. You're probably collecting names to persist the list of names on the backend, and Ember Data is the way to do it.

like image 57
Andrey Mikhaylov - lolmaus Avatar answered Mar 03 '23 13:03

Andrey Mikhaylov - lolmaus