我是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();
});
Run Code Online (Sandbox Code Playgroud)
我的休息服务返回下一个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
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
在调试器中,我看到请求已发送到REST服务并收到响应,如何查看entityList集合是否填充了收到的数据?在调试器中,entityList.models在entityList.fetch()之后为空;
我是正确的方式还是我的代码有问题?
kul*_*esa 83
我想你是在正确的道路上.但由于Backbone.Collection.fetch()是异步,你应该entityList.models在方法调用之后检查不正确的值,但是在successfetch的回调中.
也就是说,此代码会说模型列表为空:
entityList.fetch();
console.log(entityList.models); // => 0 (collection being fetched)
Run Code Online (Sandbox Code Playgroud)
虽然此代码将在填充时打印集合中的模型数量:
entityList.fetch({success: function(){
console.log(entityList.models); // => 2 (collection have been populated)
}});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30921 次 |
| 最近记录: |