3

我正在尝试在我的应用程序中添加和推送其他对象。我已经在这个jsBin中重现了这个案例

为了实现这一点,我遵循了本教程,这正是我想要的。

我有一张发票清单,任何发票都是由交易组成的。我可以在我的发票创建路线中创建一张新发票,我想在其中添加和推送任何单个交易。

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

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

在我的模板中,这是它的外观

<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>

不幸的是,我在控制台中看不到错误。我不知道出了什么问题。

如果从您删除的模板中{{#each controller}}{{/each}},您可以看到一笔交易。

我的代码有什么问题?

4

3 回答 3

2

Embers#each助手像这样切换当前范围:

// this context is the controller
{{#each controller}}
 <td>{{name}}<td/> // this context is each transaction
{{/each}}

因此,每当您尝试访问时,您都会controllers尝试在不存在的事务对象上访问它。这在您所遵循的教程中起作用的原因是那里的人没有尝试访问控制器属性。不用担心,这会让很多人感到困惑,因此将在未来的 ember 版本中被弃用。

要解决您的问题,只需使用

// this context is the controller
{{#each transaction in controller}}
 <td>{{transaction.name}}<td/> // this context is still the controller
{{/each}}

或在您的特定用例中:

<tr>
{{#each transaction in controller}}
  <td>{{transaction.name}} {{input type=checkbox value=transaction.isDone checked=transaction.isDone}} {{input valueBinding=transaction.quantity}} {{view Em.Select prompt="test" contentBinding="controllers.fare.content" optionLabelPath="content.name" optionValuePath="content.id" selectionBinding="controllers.fare.selectedFare" }}</td>
{{/each}}
</tr>
于 2014-12-18T07:37:16.320 回答
2

我做了一些更改,但它需要改进,请随时提出进一步的问题来改进它。另请参阅 emberjs 指南todo 示例。可能教程已过时,请参阅Ember store.push with hasMany 不更新模板?.

我重构了你的 add 方法,如下所示:

add: function() {

  var transactionRecord = this.store.createRecord('transaction', {
    name: 'new transaction'
  });

  return this.get("model.transactions").addObject(transactionRecord);
}

循环交易的模板是这样的:

{{#each model.transactions}}

最后,我添加了invoices/index模板,以便您在单击发票时可以查看发票及其交易:

<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>

示例:http: //jsbin.com/gugukewaka/1/edit

于 2014-12-20T17:18:11.077 回答
1

在您使用的发票/编辑模板中

{{#each controller}}

但你InvoicesCreateControllerObjectController导致问题的原因。要么不要#each在模板中使用,因为我不明白为什么需要它,或者如果真的需要它,那么将其更改InvoicesCreateControllerArrayController.

于 2014-12-24T07:16:55.950 回答