2014-03-13 28 views
0

我試圖建立以下觀點與Ember.js:Ember.js得到複合的數據對每個項目

Users: (x in total) 

* User 1: y Posts 
* User 2: z Posts 

我創建了一個itemController,負責讓每個職位的數目用戶。

App.IndexItemController = Ember.ObjectController.extend({ 
    postCount: function() { 
    var posts = this.get('content').get('posts'); 
    return posts.get('length'); 
    }.property() 
}); 

關於jsbin的完整代碼。

不知何故,我總是得到每個用戶0職位,我想這是因爲關係不正確解決在this.get('content').get('posts')。什麼是正確的方式來做到這一點?或者我會完全錯誤的方式?

獎勵問題:我可以傳遞給property()什麼,我應該傳遞一些信息給它?

回答

1

你需要設置你的計算屬性的相關鍵,你的情況content.posts.length。所以postCount知道什麼時候需要更新。現在

App.IndexItemController = Ember.ObjectController.extend({ 
    postCount: function() {  
    var posts = this.get('content').get('posts'); 
    return posts.get('length'); 
    }.property('content.posts.length') 
}); 

您的計算機屬性是正確的,但沒有數據被加載,出現這種情況是因爲沒有與用戶相關聯的帖子,沒有在user -> post方向。所以,你需要將其添加在夾具:

App.User.FIXTURES = [ 
    { 
    id: 1, 
    name: 'Jon', 
    nick: 'Jonny', 
    posts: [1] 
    }, 
    { 
    id: 2, 
    name: 'Foo', 
    nick: 'Bar', 
    posts: [2] 
    } 
]; 

這將引發一個錯誤Uncaught Error: Assertion Failed: You looked up the 'posts' relationship on '<App.User:ember280:1>' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)後。 灰燼數據確定你有一個異步的關係,並警告您設置屬性與async: true

App.User = DS.Model.extend({ 
    name: DS.attr('string'), 
    nick: DS.attr('string'), 
    posts: DS.hasMany('post', { async: true }) 
}); 

此更新的jsbin

+0

嘿感謝您的回答!這是否意味着'posts'屬性包含用戶創建的所有帖子的ID? – wowpatrick

+0

不客氣。如果你有一個id等於1的用戶實例,'user.get('posts')'將獲取與他的用戶相關的帖子,按照上面的例子,它將檢索一個ID爲1的帖子。請記住因爲我們使用'async:true'來返回'user.get('posts')',不是郵件本身,而是一個承諾。所以你需要使用'user.get('posts')。then(function(posts){posts [0]/* post instance * /})' –

+0

當然你只需要與prommise交互,如果你想要加載控制器內部的帖子,路由等。在模板內部,只需使用路徑引用對象即可,而且ember將足夠智能以處理異步代碼 –

相關問題