[英]Ember-Model EmbeddedHasManyArray not updating in template's each helper
[英]Updating a view whenever there's new records with Ember-Model
我有一個簡單的Ember.js應用程序。 有一個application view
,在該視圖內有一個results view
。
我正在使用ember-model以這種方式從服務器獲取JSON:
Map.Winery = Ember.Model.extend({
name: Ember.attr(),
address: Ember.attr(),
address_2: Ember.attr(),
city: Ember.attr(),
stateprovince: Ember.attr(),
country: Ember.attr(),
latitude: Ember.attr(),
longitude: Ember.attr(),
full_address: function () {
return this.get('address') + ' ' + this.get('city') + ' ' + this.get('stateprovince') + ' ' + this.get('country');
}.observes('address', 'city', 'stateprovince', 'country')
});
Map.Winery.adapter = Ember.Adapter.create({
findAll: function(klass, records) {
return Ember.$.getJSON('/api/wineries').then(function(response) {
if (response.success) {
records.load(klass, response.data);
}
});
}
});
我使它盡可能的簡單,以便人們可以對發生的事情有個公正的了解。
因此,基本上,我在應用程序視圖中有一個按鈕,每當我單擊該按鈕時,都會調用一個調用Map.Winery.findAll()的操作; (從服務器重新加載數據)。
我想要的是,每當記錄中加載了新數據時, results view
應使用新結果進行更新。
application.hbs
<button class="locate" {{action "reload" on="click"}}>Reload</button>
{{view Map.ResultsView}}
application_controller.js
Map.ApplicationController = Ember.ObjectController.extend({
actions: {
reload: function() {
var results = Map.Winery.findAll();
}
}
});
results.hbs
<div class="results">
{{#each results}}
<p>{{this}}</p>
{{/each}}
</div>
results_view.js
Map.ResultsView = Ember.View.extend({
templateName: 'results',
didInsertElement: function(e) {
}
});
現在的問題是:如何做到這一點,以便每當有新數據從服務器加載到記錄時,結果視圖都會更新?
我嘗試插入盡可能多的相關代碼,請隨時提出任何問題。
謝謝
只需將新對象推入您的集合中即可(或使用findAll中的新集合替換該集合)。
http://emberjs.jsbin.com/EFiTOtu/1/edit
App.IndexController = Em.ArrayController.extend({
actions: {
addNewColor: function(){
this.get('model').pushObject(this.get('newColor'));
}
}
});
我發現最好的方法是將事件添加到需要觸發的任何事件中,並在需要時使用該觸發器。
使用Ember.Evented
:
App.ApplicationController = Ember.ObjectController.extend(Ember.Evented, {
viewUpdated: function(args) {}
/* controller stuff here */
});
現在,我幾乎可以在任何地方添加這樣的事件:
this.get('controller').on('viewUpdated', $.proxy(this.viewUpdated, this));
因此,每當我必須觸發視圖更新時,我都會執行以下操作:
this.get('controllers.application').trigger('viewUpdated', args);
(順便說一句,args是可選的)
這樣,無論何時我想觸發事件。 它不像觀察員那么強大,但仍然可以很好地完成工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.