Search code examples
javascriptember.jsjsfiddlejsbin

Add and push additional objects on the fly with Ember


I am trying to add and push additional objects in my application. I have reproduced the case in this jsBin

To Achieve that I have followed this tutorial, which does exactly what I want.

I have a list of invoices and any invoice is composed by transactions. I can create a new invoice in my invoices create route where I want to add and push any single transaction.

  actions: {
    add: function() {
      var newTransaction = Ember.Object.create({
        name: "New Transaction",
        quantity: null,
        selectedFare: null,
        isDone: false
      });

      return this.get("content").pushObject(newTransaction);
    }

In my template this is how it looks

<tr>
{{#each controller}}
  <td>{{name}} {{input type=checkbox value=isDone checked=isDone}} {{input valueBinding=quantity}} {{view Em.Select prompt="test" contentBinding="controllers.fare.content" optionLabelPath="content.name" optionValuePath="content.id" selectionBinding="controllers.fare.selectedFare" }}</td>
{{/each}}
</tr>

Unfortunately I can not really see the error in the console. I don't know what is going wrong.

If from the template you remove{{#each controller}}{{/each}}, you can see one single transaction.

What's wrong in my code?


Solution

  • I made some changes, but it needs improvement, feel free to ask further questions to improve it. Also see the emberjs guides todo example. Probably the tutorial is outdated see Ember store.push with hasMany doesn't update template?.

    I refactored your add method like this:

    add: function() {
    
      var transactionRecord = this.store.createRecord('transaction', {
        name: 'new transaction'
      });
    
      return this.get("model.transactions").addObject(transactionRecord);
    }
    

    The template to loop transactions is like this:

    {{#each model.transactions}}

    Finally I added invoices/index template so you can see the invoices and their transactions, when you click an invoice:

    <script type="text/x-handlebars" data-template-name="invoice/index">
      <p> Invoice Index Route</p>
      <p> {{title}} </p>
      <p> Transactions: </p>
        {{#each transactions}}
          <ul>
            <li> name: {{name}} </li>
            <li> quantity: {{quantity}} </li>
          </ul>
        {{/each}}
    </script>
    

    The example: http://jsbin.com/gugukewaka/1/edit