Emberjs-1.0.0-rc.6 click to dynamically add more o

2019-06-03 09:15发布

问题:

I want to create a form where uses can click a button to add additional input fields. I have created a partialy working here jsfidle and the entire code in the jsfiddle is pased below:

I have 3 problems:

  1. This adds a textfield but is not using ember bindings $("#addField").append('
    ')
    . When I try to the version that relies on handlebars I means this: ** $("#addField").append('{{textArea value=name}}
    '), instead of the output being a **textArea, I get just {{textArea value=name}}

  2. Since the added fields will be essentially thesame field as the ones in the form already, how do I ensure anything typed into it is distinct to that field. In the attached because the textfield input and textArea tags have value=name, anything I type in the textfield will appear in the textArea. I know this qwill apply even if I use valueBinding=controller.name or if is the views property with valueBinding=view.name. How do I keep the value of each additional input field added with a click unique to it.

The entire code in the jsfiddle

 App = Ember.Application.create();

 App.ApplicationView = Ember.View.extend({
  templateName: 'application',
  attributeBindings: ['id'],
  id: "addField",

  moreFields: function(){
    $("#addField").append('<input type="text"  value=name /><br/>');

    $("#addField").append('{{textArea value=name}}<br/>');  
  }

});

The template:

 <script type="text/x-handlebars" data-template-name='application'>
    <h1> Hello</h1>
    {{input value=name}}
    <br/>
    {{textarea value=name}}
    <br/>
   {{input type=checkbox checked=isActive}}
   <br/>

  <button {{action 'moreFields' target='view'}}> click for more field </button>
   <br/>
  {{outlet}}
</script>

Here is a jquery based demo by someone else, demonstrating what I hope to achieve, that is what you type into each new field you add remaining distinct: http://jsfiddle.net/qBURS/2/

working solution:

Augmented the jsfiddle provided by Selva-G'. Added the removeFields() method that removes any added fields and a save() method that just logs the content we intend to pass via the submitted form.

回答1:

You cannot use raw jQuery like this. Just try to loop over an array to draw your form elements. When you want to add more fields , just push the content to the array. Emberjs is smart enough to detect the changes to draw your new fields.. In you hbs ,

   {{#each view.content}}
    {{input value=name}}
    {{textarea value=name}}
   {{input type=checkbox checked=isActive}}
  {{/each}}

When you click more fields just update the content array like

        this.get('content').pushObject({name: ''});

Sample fiddle

Hope this helps