问题
I am pushing records into my store using websockets.
I am displaying items on the screen via a handlebars template
{{#each item in items}}
<div>{{item.name}}</div>
{{/each}}
In my controller I have the items collection
items : function() {
var items = this.store.find('items');
return items.filterBy({type : "NEW"});
}.property()
Now, when new records are added to the store, I need to update the items automatically.
items : function() {
var items = this.store.find('items');
return items.filterBy({type : "NEW"});
}.property('??????')
So is there some way of listening to the store when records are added via a computed property. Ideally I would like to listen to models of a particular type.
回答1:
The best way to do this is to do:
items : function() {
return this.store.filter(function(item){
return item.get('TYPE') === 'NEW';
});
}.property()
store.filter
returns a live array that updates whenever there are any changes in the store, so it will respond to the new records beings pushed.
回答2:
Im assuming you are using an array controller. You just need to observe the content array like content.[]
. So your controller code should look like
App.IndexController = Em.ArrayController.extend({
filteredContent: function() {
return this.get('model').filterBy('type', 0);
}.property('model.[]')
});
And use the filteredContent
in the template
{{#each filteredContent}}
<li>{{title}} - {{songCount}}</li>
{{/each}}
Here is a working bin.
来源:https://stackoverflow.com/questions/25324121/listening-when-new-records-are-added-to-the-store-via-a-computer-property