I've followed the PeepCode tutorial on Ember.js, and am extending it to remove items from the tab. I'm also implementing a simple RESTful interface on the server to persist changes, and am using DS.RESTAdapter.
There are 2 relavent models:
- TabItem
- Tab, with a hasMany relationship to TabItem
Following on from the tutorial, I've added a simple remove link to the tab template:
<script type="text/x-handlebars" data-template-name="tab">
<ul id="customer-tab">
{{#each tabItem in tabItems}}
<li>
<h3><a href="#" {{ action "removeTabItem" tabItem }}>x</a> {{ tabItem.food.name }} <span>{{ money tabItem.cents}}</span></h3>
</li>
{{ else }}
<li><h3>Click a food to add it</h3></li>
{{/each}}
<li id="total">
<h3>Total <span>{{ money cents }}</span></h3></li>
</li>
</ul>
</script>
And in the controller
App.TabController = Ember.ObjectController.extend({
removeTabItem: function(tabItem) {
var store = this.get('store');
store.transaction();
var t = store.find(App.TabItem,tabItem.get('id'));
t.deleteRecord();
this.get('tabItems').removeObject(tabItem);
store.commit();
}
});
The above controller code I did by a bit of trial & error & guesswork. The "removeObject" call seems to be necessary to properly remove the item from the user interface, and the "deleteRecord" call seems to be necessary so "commit" will then result in a DELETE call to the server.
The controller code seems a bit long-winded though, and I suspect I'm missing something. Is there a way that is deemed better, maybe using the "tabItem" more directly, and using fewer API calls?