2014-03-13 6 views
0

에 대한 화합물 데이터를 얻을 수 사용자.Ember.js 내가 Ember.js 다음과 같은보기를 구축하기 위해 노력하고있어 각 항목

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 방향으로 아니, 사용자와 관련된 게시물이 없기 때문에, 이런 일이로드되지 않습니다. 그래서 당신은 고정에 추가해야합니다 오류가 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 })`)를 발생이 후

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

합니다. 엠버 데이터는 답변이 업데이트 된 jsbin

+0

안녕하세요 덕분에 당신은 비동기 관계를 가지고 있음을 확인하고, async: true

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

와 설정에 속성을 경고! 이것은'posts' 속성이 사용자가 생성 한 모든 게시물의 ID를 포함한다는 것을 의미합니까? – wowpatrick

+0

당신은 환영합니다. id가 1 인 사용자 인스턴스가 있다면 'user.get ('posts ')'는 위 예제에 따라 사용자와 연결된 게시물을 가져오고 id 1의 게시물이있는 배열을 가져옵니다. 우리가'async : true'를 사용하고 있기 때문에'user.get ('posts')'의 반환은 게시물 그 자체가 아니라 약속입니다. (post (post) {posts/post instance * /})' –

+0

물론 prommise와 상호 작용할 필요가 있습니다. 컨트롤러, 경로 등의 내부에 게시물을로드하고 싶습니다. 템플릿 내부에서 경로를 사용하여 객체를 참조하는 것이 좋으며 ember는 비동기 코드를 처리 할만큼 똑똑 할 것입니다 –