![](/img/trans.png)
[英]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.