2014-09-05 40 views
1

我有一个消息列表。当一个特定的消息被点击时,它会加载细节。这部分工作正常。Ember - 嵌套视图中的异步数据

我想加载点击消息时异步加载其他一些相关的数据。为此,我在我的messageView中筑巢了一个视图。但是我无法加载和访问数据。

这是我的模板

<script type="text/x-handlebars" id="message"> 

    {{#view "messageThread" contentBinding="this"}} 

     {{#each message in view.getConversation}} 

     <div>Message body</div> 
     {{message.body}} 

     {{/each}} 


    </div> 
    {{/view}} 

</script> 

这里是在模板中使用上述

App.MessageThreadView = Ember.View.extend({ 


    getConversation: function(){ 

     var msg = this.get('context').model; 

     var sender_id = msg.sender.id; 
     var recipient_id = msg.recipient.id; 

     downloadConversation(recipient_id, sender_id); 

     return this.get('current_conversation'); 

    }.property('current_conversation'), 

}); 

这里messageThreadView被称为按上述观点来看

function downloadConversation(recipient_id, sender_id){ 

    $.getJSON(<a url>) 
    .then(function(data){ 

     App.set('current_conversation', data['objects']); 
    }); 

} 

异步数据负载函数我如何得到view.getConversation按预期工作,即负载吨数据何时可用?

回答

1

以下是异步属性的最简单模式,尤其是当它们是集合时。你基本上返回一个集合引用(在这种情况下是convo),然后你从引用异步地填充该集合。

App.MessageThreadView = Ember.View.extend({ 
    getConversation: function(){ 

     var msg = this.get('context').model, 
      sender_id = msg.sender.id, 
      recipient_id = msg.recipient.id, 
      convo = []; 

     $.getJSON(<a url>).then(function(data){ 
     data.forEach(function(item){ 
      convo.pushObject(item); 
     }); 
     }); 

     return convo; 
    }.property(), // this should be watching sender and receipient 

}); 
+0

Thanks!这工作。 – 2014-09-06 06:43:17

+0

如何使查看更改发件人/收件人?我尝试添加发件人/收件人作为视图的属性,并在getConversation方法内执行一组操作。似乎没有工作。有什么建议? – 2014-09-08 13:44:57

+1

'property('context.sender.id','context.recipient.id')'...我假设你将控制器传递给contextBinding中的视图,所以你可以跳过模型步骤 – Kingpin2k 2014-09-08 14:35:39