I am trying to wrap my head around ember.js. I am writing a little web app that displays the prices for certain coffee beans. Users can add new coffee beans, but now I want to give users the ability to edit existing coffee beans. If a user double clicks on a bean's entry, then he or she should be able enter either a new name or price:
<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>
Here is the code for the 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);
}
}
});
Here is the link to the JS Fiddle: http://jsfiddle.net/cspears2002/y8MT3/
Double clicking a name or a price does get me into the editCoffee function, but I am not able to edit the coffee beans for some reasons. Any ideas?
There are a couple of problems. isEditing
should live outside of the actions
hash, and isEditing
doesn't really exist on the ArrayController
since the property is relevant to a single item, not the entire array. That being said an item controller would be an appropriate thing to use here. In ember you can tell the array controller that there is an item controller that it should use when iterating over a list of items. One last note, tables cause a ton of problems in ember since it removes and insert dom into the page and depending on the browser this can cause a slew of problems with tables. So I ripped out all of the table stuff for the sake of showing you how to fix it.
App.CoffeeItemController = Em.ObjectController.extend({
isEditing: false,
actions: {
editCoffee: function () {
this.toggleProperty('isEditing');
}
}
});
App.CoffeeController = Ember.ArrayController.extend({
itemController: 'coffeeItem'
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.