gpt4 book ai didi

rest - Backbone.js + 休息。 fetch() 之后不会填充集合

转载 作者:行者123 更新时间:2023-12-03 07:37:28 25 4
gpt4 key购买 nike

我是 Backbone 新手。所以我尝试从 REST 服务获取数据。

这是我的简单代码:

$(function () {

var Entity = Backbone.Model.extend({
url: function() {
return 'http://localhost:8080/rest/entity/'+this.id;
}
});

var EntityList = Backbone.Collection.extend({
model: Entity,
url: 'http://localhost:8080/rest/entity'
});

var entityList = new EntityList();

entityList.fetch();

});

我的休息服务返回下一个 JSON:

[{"id":1387,
"version":3,
"entityName":"entity01",
"entityLabel":"Entity01",
"entityPluralLabel":"Entity01",
"attributes":
[{"id":1425,
"slot":"D001",
"version":0,
"attributeName":"dfield",
"attributeType":
{"id":7,
"description":"Date",
"attributeType":"date",
"databaseType":"DATE"
},
"options":[],
"order":2,
"attributeLabel":"dField",
"checked":null
},
{"id":1424,
"slot":"S001",
"version":0,
"attributeName":"txfield",
"attributeType":
{"id":1,
"description":"Textbox",
"attributeType":"textbox",
"databaseType":"STRING"
},
"options":[],
"order":1,
"attributeLabel":"txField",
"checked":null
}
]
},
{"id":1426,
"version":3,
"entityName":"entity02",
"entityLabel":"Entity02",
"entityPluralLabel":"Entity02",
"attributes":
[{"id":1464,
"slot":"D001",
"version":0,
"attributeName":"dfield",
"attributeType":
{"id":7,
"description":"Date",
"attributeType":"date",
"databaseType":"DATE"
},
"options":[],
"order":2,
"attributeLabel":"dField",
"checked":null
}
]
}
]

在调试器中,我看到请求已发送到 REST 服务并且已收到响应,如何查看entityList 集合是否填充了收到的数据?在调试器中,entityList.models 在entityList.fetch()之后为空;

我的方法正确还是我的代码有问题?

最佳答案

我认为你的做法是正确的。但由于 Backbone.Collection.fetch() 是异步的,因此您应该在方法调用后而不是在成功时检查实体列表模型的值> 获取回调。

也就是说,这段代码会说模型列表为空:

entityList.fetch();
console.log(entityList.models); // => 0 (collection being fetched)

虽然此代码将在填充后打印集合中的模型数量:

entityList.fetch({success: function(){
console.log(entityList.models); // => 2 (collection have been populated)
}});

关于rest - Backbone.js + 休息。 fetch() 之后不会填充集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7259712/

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