2013-10-21 20 views
1

我有一个简单的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) { 
    } 

}); 

现在的问题是:我如何使它所以每当有从服务器加载到的记录,结果视图的新数据得到更新?

我尝试插入尽可能多的相关代码,随时提出任何问题。

感谢

回答

0

我发现最好的办法是将事件添加到任何我需要被触发,使用触发每当我需要它。

使用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是可选的)

这种方式只要我想要触发事件。它并不像观察者那样强大,但它仍能很好地完成这项工作!

0

刚刚推新对象到您的收藏(或从的findAll新的集合取代集合)。

http://emberjs.jsbin.com/EFiTOtu/1/edit

App.IndexController = Em.ArrayController.extend({ 
    actions: { 
    addNewColor: function(){ 
     this.get('model').pushObject(this.get('newColor')); 
    } 
    } 
});