簡體   English   中英

JavaScript:Backbone.js填充模型集合

[英]JavaScript: Backbone.js populate collection of models

這是我到目前為止:

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']並返回所需信息,但是我不知道為什么集合沒有被填充。

ItemListparse函數中,它正確顯示了我的所有輸出,但它沒有做任何事情。

我在代碼中留下了一些注釋,以獲得更精確的問題,但主要的問題是為什么集合不會填充明顯接收到的數據

將您的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;
}

您需要在執行任何必要的解析后返回數據的解析方法。

解析的常見用例是,如果您要發回一個表單的對象,例如:

{ "id" : "NaN", "tasks": [ *all your models in a list here *] }

然后你會像這樣使用解析:

parse: function (data) {
    return data.tasks
}

然后Backbone處理剩下的事情。

是否有一個特殊原因導致您以字典格式發回數據? 目前還不清楚你打算如何將它映射到集合的每個模型。 關鍵是無關緊要的嗎? 如果是這樣,你應該傳回值中的對象列表。(盡管見底部注釋)。 如果沒有,並且您想將其附加到模型,則應將其移動到您用作值的對象並發回列表。

*注意:實際上不要發回JSON列表。 GET請求有一個漏洞,它依賴於列表本身就是有效的javascript,惡意站點可以使用Array對象並覆蓋它以使用腳本標記到API以使用用戶憑據來提取任何可用的信息在那個電話里。 相反,當想要發回一個列表時,你應該使用這樣的東西:

{ result: [*list here*] }

然后你只需使用上面的解析方法來提取列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM