我是Backbone.js的新手,觉得我必须遗漏一些非常基本的东西。我试图了解如何设置可以检索数据的模型/集合。为此,我实例化一个模型/集合,然后立即调用fetch()来填充它(我知道引导第一个调用是最好的做法,但我现在只想了解fetch())。我创建的示例模型确实启动了对RESTful服务的网络调用,但是在获取调用后它仍然处于Pending状态,并且从未到达fetch调用中的成功回调,因此模型永远不会获取任何数据
这是我的js代码:
var MyProducts = Backbone.Collection.extend({
url: contextPath + "/carousel.json"
});
var MyProductsCollection1 = Backbone.Collection.extend({
urlRoot: contextPath + "/carousel.json",
url: contextPath + "/carousel.json"
});
var MyProductsCollection2 = Backbone.Collection.extend({
url: contextPath + "/carousel.json"
});
var MyView = Backbone.View.extend({
render: function () {
console.log('this.collection');
console.log(this.collection);
return this;
}
})
var myProducts;
var myProductsCollection1;
var myProductsCollection2;
$(function () {
myProducts = new MyProducts();
myProducts.fetch({
success: function (model) {
var result = model.get("records");
}
});
myProductsCollection1 = new MyProductsCollection1();
myProductsCollection1.fetch({
success: function (model) {
var result = model.get("records");
}
});
myProductsCollection2 = new MyProductsCollection2();
myProductsCollection2.fetch({
success: function (model) {
var result = model.get("records");
}
});
var myView1 = new MyView({ collection: myProductsCollection1 });
var myView2 = new MyView({ collection: myProductsCollection2 });
console.log('view1');
myView1.render();
console.log('view2');
myView2.render();
});
这是控制台输出,在我看来,它表明没有从fetch()调用中检索到记录:
view1
this.collection
child {length: 0, models: Array[0], _byId: Object}
view2
this.collection
hild {length: 0, models: Array[0], _byId: Object}
在“网络”标签中,有3个请求发送到carousel.json,但所有显示状态为“待定”,表示它们未完成。
REST api的域名与网站的域名相同(我称之为Spring控制器,用于检索两个视图和此JSON),因此不应存在任何跨域问题。)
以下是邮递员致https://mydomain/mycontextdir/carousel.json的一些结果。 (实际结果集更长,但格式相同):
{
"records": [
{
"properties": [
{
"name": "pDefaultCatgroupID",
"value": "1000357"
},
{
"name": "highPriceFormatted",
"value": "$7.95"
},
{
"name": "REG_HIGH_PRICE",
"value": "7.950000"
}
]
},
{
"properties": [
{
"name": "REG_LOW_PRICE",
"value": "13.950000"
},
{
"name": "pItemID",
"value": "1254778"
}
]
}
],
"navigableFacets": null,
"refinmentFacets": null,
"breadcrumbs": [],
"content": null,
"totalRecords": 5868,
"navigationPath": [],
"searchReport": {
"fault": {
"hasFault": false,
"faultCommandName": null,
"faultCode": null,
"faultStatus": null,
"faultMessageKey": null,
"faultMessage": null,
"errors": null
},
"commerceId": null,
"loggedInCommerce": false,
"terms": null,
"autoSuggestion": null,
"profanity": false
}
}
我做错了什么阻止了数据的检索?
非常感谢您的协助!
答案 0 :(得分:1)
看起来你混淆了从Model获取来自Collection的提取(注意传递给成功回调的参数的差异)。当您对集合调用fetch时,集合需要返回一个模型数据数组,如果数据不符合该格式,则可以覆盖它的parse函数来处理数据。因为你的json实际上是一个对象而不是一个数组,你需要自己解析它。
所以在你的情况下你想要做的是
var MyProducts = Backbone.Collection.extend({
url: contextPath + "/carousel.json",
parse: function (data) {
return data.records;
}
});
var myProducts = new MyProducts();
myProducts .fetch({
success: function (collection, response, options) {
alert(collection.length);
});
以下是指向jsbin
的链接