我似乎無法得到JSON被加載到我的FriendsCollection渲染成FriendListView渲染。我可以看到它通過網絡面板加載,並且可以將數據記錄到控制檯,但由於某些原因,fetch命令未將數據傳遞到要呈現的視圖。骨幹 - 裝載JSON到集合將不會在視圖
我使用骨幹1.0。
我使用的代碼可以在這裏jsbin:http://jsbin.com/OHePaki/1/edit?html,js,output
// MODELS
var ArtifactModel = Backbone.Model.extend({
initialize: function() {
this.on('reset', function(){ artifactView.render() })
},
defaults: {
"text": "Unknown Text",
"timestamp": "Unknown timestamp"
}
});
var artifactModel = new ArtifactModel();
// COLLECTIONS
var ArtifactCollection = Backbone.Collection.extend({
model: ArtifactModel,
url: '/getDigest.json',
// url: 'http://we365.local/Artifact/GetShareableArtifact?token=b88d2640826bb8593f6edb308ce604f28225f240&artifact_id=2&social_site=tw&log_inside=&go',
parse: function(data) {
console.log('running parse');
return _.map(data.response.content, _.identity);
},
initialize: function(){
this.on('reset', function(){ artifactListView.render(); }),
console.log('running init function for ArtifactCollection');
this.fetch();
//this.reset(artifactjson, { parse: true });
console.log(this.toJSON());
}
});
var artifactCollection = new ArtifactCollection();
// VIEWS
var ArtifactView = Backbone.View.extend({
tagName: 'li',
className: 'single-model',
render: function(){
var template = Handlebars.compile($('#stream_getDigest').html());
this.$el.html(template(this.model.toJSON()));
return this;
}
});
var ArtifactListView = Backbone.View.extend({
initalize: function(){
this.collection.on('add', this.addOne, this);
},
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(artifactModel){
var artifactView = new ArtifactView({model: artifactModel});
this.$el.append(artifactView.render().el);
}
});
// rendering
var artifactView = new ArtifactView({model: artifactModel});
var artifactListView = new ArtifactListView({collection: artifactCollection});
artifactView.render();
artifactListView.render();
$('#list').html(artifactListView.$el.html());
謝謝@BMH,這實際上很有意義。雖然我無法相信我沒有發現任何可能是問題的地方。再次感謝! – flashpunk
這是正確的嗎?我知道(默認情況下)代碼在不等待AJAX響應的情況下繼續運行,但是我認爲'reset'事件在模型更新後被觸發,而不是在請求發送後立即觸發。在這種情況下,它應該沒有'{async:false}'位。 –
@DavidKnipe是的,它可以使用'this.fetch({reset:true});',但你可能需要調用'$('#list')。html(artifactListView。$ el.html()); '再次看到它在瀏覽器中生效。 – BMH