JavaScript:Backbone.js填充模型集合

Bri*_*ham 4 javascript php collections json propel

这是我到目前为止:

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();
Run Code Online (Sandbox Code Playgroud)

当前(预期)的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"}
}
Run Code Online (Sandbox Code Playgroud)

这成功地进行了民意调查page.php并且后端作用$_SERVER['REQUEST_METHOD']并返回所需信息,但是我不知道为什么集合没有被填充.

在它的parse功能ItemList正确显示我所有的输出,但它没有做任何事情.

我在代码中留下了一些注释,以获得更精确的问题,但主要的问题是为什么集合不会填充明显接收到的数据

ggr*_*ner 8

将您的parse方法修改为:

parse: function(response){
   var parsed = [];
   for(var key in response){
      parsed.push(response[key]);
   }
   return parsed;
}
Run Code Online (Sandbox Code Playgroud)

要遵循惯例,请将list内部更改ItemViewmodel.也在render():

render: function() {
    var template = _.template("<div>some template</div>");
    this.model.each(function(item){ 
        this.$el.append(template(item.toJSON()));
    }, this);
    return this;
}
Run Code Online (Sandbox Code Playgroud)