gpt4 book ai didi

javascript - this.collection.each 不迭代

转载 作者:行者123 更新时间:2023-11-30 10:30:39 25 4
gpt4 key购买 nike

我试图了解 Backbone 并尝试创建一些前端的小型 REST API,但无法让 View 工作。

fetch() 返回包含三个元素的有效 JSON 数组。并且 this.collection.models 不是空的 (typeof object - []) - 它里面有树子对象元素。但是 each 迭代不会触发。

当使用 console.log(this.collection.models); 检查 collection.models 是否存在时,看起来一切正常:

console.log(this.collection.models)

如有任何建议,我将不胜感激!

var Account = Backbone.Model.extend({});

var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts',
initialize: function () {
this.fetch();
}
});

var AccountsView = Backbone.View.extend({
render: function() {

// Check if there is something
console.log(this.collection.models);

// This doesn't work
_.each(this.collection.models, function(model) {
console.log(model);
});

// Neither this
this.collection.each(function(model) {
console.log(model);
});
}
});


var a = new AccountsView({collection: new AccountsCollection()});
a.render();

最佳答案

第一个选项

var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts'
});

var AccountsView = Backbone.View.extend({
render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

collection.fetch().done(function () {
// collection has been fetched
view.render();
});

第二个选项

var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts'
});

var AccountsView = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
},
render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

第三个选项

var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts',
initialize: function () {
this.deferred = this.fetch();
}
});

var AccountsView = Backbone.View.extend({
initialize: function() {
this.collection.deferred.done(_.bind(this.render, this));
},
render: function() { /**/ }
});

var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

关于javascript - this.collection.each 不迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com