2013-10-20 4 views
12

로컬 API에서 내 백본 컬렉션을 채우고 뷰를 변경하여 데이터를 표시하려고합니다. 내 컬렉션에있는 fetch() 호출이 성공한 것으로 보이고 데이터를 가져 오지만 가져 오기 작업은 컬렉션의 모델을 업데이트하지 않습니다.백본 컬렉션에서 데이터를 가져 오지만 모델을 설정하지 않습니다.

var Book = Backbone.Model.extend(); 

var BookList = Backbone.Collection.extend({ 

    model: Book, 
    url: 'http://local5/api/books', 

    initialize: function(){ 
     this.fetch({ 
      success: this.fetchSuccess, 
      error: this.fetchError 
     }); 
    }, 

    fetchSuccess: function (collection, response) { 
     console.log('Collection fetch success', response); 
     console.log('Collection models: ', this.models); 
    }, 

    fetchError: function (collection, response) { 
     throw new Error("Books fetch error"); 
    } 

}); 

내가 이렇게 내 의견을했습니다 :이 같은

var BookView = Backbone.View.extend({ 

    tagname: 'li', 

    initialize: function(){ 
     _.bindAll(this, 'render'); 
     this.model.bind('change', this.render); 
    }, 

    render: function(){ 
     this.$el.html(this.model.get('author') + ': ' + this.model.get('title')); 
     return this; 
    } 

}); 

var BookListView = Backbone.View.extend({ 

    el: $('body'), 

    initialize: function(){ 
     _.bindAll(this, 'render'); 

     this.collection = new BookList(); 
     this.collection.bind('reset', this.render) 
     this.collection.fetch(); 

     this.render(); 
    }, 

    render: function(){ 
     console.log('BookListView.render()'); 
     var self = this; 
     this.$el.append('<ul></ul>'); 
     _(this.collection.models).each(function(item){ 
      console.log('model: ', item) 
      self.appendItem(item); 
     }, this); 
    } 

}); 

var listView = new BookListView(); 

내 API 반환 JSON 데이터

내가 나의 모델과 수집에있어 무엇 : 이 코드를 실행하면

[ 
    { 
     "id": "1", 
     "title": "Ice Station Zebra", 
     "author": "Alistair MacLaine" 
    }, 
    { 
     "id": "2", 
     "title": "The Spy Who Came In From The Cold", 
     "author": "John le Carré" 
    } 
] 

나는 콘솔이 얻을 :

BookListView.render() app.js:67 
Collection fetch success Array[5] 
Collection models: undefined 

내게 가져 오기 호출이 데이터를 가져오고 있지만 모델로 채워지지 않았 음을 나타냅니다. 아무도 내가 여기서 뭘 잘못하고 있다고 말할 수 있습니까?

답변

12

fetchSuccess 함수는 collection.models이 아니고 this.models이어야합니다.

console.log('Collection models: ', collection.models); 

@Pappa의 제안을 고려하십시오.

+0

고맙습니다. 많은 사용자 10, 그 대답이었습니다! 난 아직도 내 길을 찾고있어 "this"가 fetchSuccess 안에 전역 범위를 가지고 있다는 것을 깨닫지 못했다. 나는 여전히 100 % 확신 할 수 없다. 그러나 "this"를 fetchSuccess에 바인드하면 찾을 수있다. 컬렉션의 범위. –

+0

'fetchSuccess'는 Backbone.js에 의해 전역 범위에서 실행되는'Backbone.sync'에 의해 호출되는 콜백입니다. – user10

+0

오오 이런 이유가 있습니다! 감사합니다 user10. –

8

BookList 컬렉션을 초기화 할 때 한 번, BookListView를 초기화 할 때 한 번씩 BookList 컬렉션에서 fetch를 두 번 호출합니다. 인스턴스가 생성되는 순간 컬렉션이 채워지는 것은 나쁜 습관으로 간주됩니다. 또한 '초기화'이벤트에 대한 응답으로 초기화 호출에서 두 번 뷰를 렌더링 한 다음 직접 호출합니다.

BookList 컬렉션에서 초기화 함수를 완전히 제거하고 this.render()에 대한 호출을 제거하는 것이 좋습니다. BookListView의 초기화 호출이 끝날 때.

+1

감사합니다. 파파, 나는 매우 유용한 조언을 구할 것입니다! –

+0

보기에 초기화 메소드가 있으면 자동으로 this.render()가 호출됩니다. –

+1

@AlexMills 아니요, 렌더링 기능을 수동으로 호출해야합니다. – Kevin

관련 문제