我正在尝试了解 ember.js。我正在编写一个小网络应用程序,显示某些咖啡 bean 的价格。用户可以添加新的咖啡 bean ,但现在我想让用户能够编辑现有的咖啡 bean 。如果用户双击 bean 的条目,那么他或她应该能够输入新名称或价格:
<script type="text/x-handlebars" data-template-name="coffee">
<table>
<tr>
<th>Beans</th>
<th>Prices</th>
</tr>
{{#each}}
<tr>
{{#if isEditing}}
<td>{{input type="text"}}</td>
<td>{{input type="text"}}</td>
<td><button class="delete">Delete</button></td>
{{else}}
<td {{action "editCoffee" on="doubleClick"}}>{{bean}}</td>
<td {{action "editCoffee" on="doubleClick"}}>{{price}}</td>
<td><button class="delete">Delete</button></td>
{{/if}}
</tr>
{{/each}}
</table>
{{input type="text" placeholder="Beans" value=newBean}}
{{input type="text" placeholder="Price" value=newPrice}}
<button type="button" {{action 'createCoffee'}}>Submit</button>
</script>
这是 Controller 的代码:
// Controllers
App.CoffeeController = Ember.ArrayController.extend({
actions: {
createCoffee: function() {
// Get the bean name
var bean = this.get('newBean');
if (!bean.trim()) { return; }
// Get the price
var price = this.get('newPrice');
if (!price.trim()) { return; }
// Create the new coffee model
var coffee = this.store.createRecord('coffee', {
bean: bean,
price: price
});
// Clear the text fields
this.set('newBean', '');
this.set('newPrice', '');
// Save the new model
coffee.save();
},
isEditing: false,
editCoffee: function () {
console.log('Hello World');
this.set('isEditing', true);
}
}
});
这里是 JS Fiddle 的链接:http://jsfiddle.net/cspears2002/y8MT3/
双击名称或价格确实可以进入 editCoffee 功能,但由于某些原因我无法编辑咖啡 bean 。有什么想法吗?
最佳答案
有几个问题。 isEditing
应该位于 actions
哈希之外,并且 isEditing
并不真正存在于 ArrayController
上,因为该属性与单个项目相关,而不是整个数组。话虽如此,这里使用项目 Controller 是合适的。在 ember 中,您可以告诉数组 Controller ,在迭代项目列表时应该使用一个项目 Controller 。最后一点,表格在 ember 中会导致大量问题,因为它会在页面中删除和插入 dom,并且根据浏览器的不同,这可能会导致表格出现一系列问题。因此,为了向您展示如何修复它,我撕掉了所有表格内容。
App.CoffeeItemController = Em.ObjectController.extend({
isEditing: false,
actions: {
editCoffee: function () {
this.toggleProperty('isEditing');
}
}
});
App.CoffeeController = Ember.ArrayController.extend({
itemController: 'coffeeItem'
....
关于javascript - 在 ember.js 中编辑模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21507497/