로컬 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
내게 가져 오기 호출이 데이터를 가져오고 있지만 모델로 채워지지 않았 음을 나타냅니다. 아무도 내가 여기서 뭘 잘못하고 있다고 말할 수 있습니까?
고맙습니다. 많은 사용자 10, 그 대답이었습니다! 난 아직도 내 길을 찾고있어 "this"가 fetchSuccess 안에 전역 범위를 가지고 있다는 것을 깨닫지 못했다. 나는 여전히 100 % 확신 할 수 없다. 그러나 "this"를 fetchSuccess에 바인드하면 찾을 수있다. 컬렉션의 범위. –
'fetchSuccess'는 Backbone.js에 의해 전역 범위에서 실행되는'Backbone.sync'에 의해 호출되는 콜백입니다. – user10
오오 이런 이유가 있습니다! 감사합니다 user10. –