这是我目前所拥有的:
var Item = Backbone.Model.extend({
defaults: {
id: 0,
pid: 0,
t: null,
c: null
},
idAttribute: 'RootNode_', // what should this be ???
url: 'page.php'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'page.php',
parse: function(data) {
alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
}
});
var ItemView = Backbone.View.extend({
initialize: function() {
this.list = new ItemList();
this.list.bind('all', this.render, this);
this.list.fetch();
},
render: function() {
// access this.list ???
}
});
var view = new ItemView();
当前(预期)json 响应:
{
"RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
"RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
"RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}
这成功地轮询了page.php
并且后端作用于$_SERVER['REQUEST_METHOD']
并返回所需的信息,但是我不知道为什么收集未填满。
在 ItemList
的 parse
函数中,它正确地显示了所有输出,但它没有做任何事情。
我在代码中为一些更精确的问题留下了一些评论,但主要问题是为什么集合中没有填充明显接收到的数据?
最佳答案
将您的parse
方法修改为:
parse: function(response){
var parsed = [];
for(var key in response){
parsed.push(response[key]);
}
return parsed;
}
为了遵循约定,将 ItemView
中的 list
更改为 model
。同样在 render()
中:
render: function() {
var template = _.template("<div>some template</div>");
this.model.each(function(item){
this.$el.append(template(item.toJSON()));
}, this);
return this;
}
关于php - JavaScript:Backbone.js 填充模型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9218394/