Backbone.Model save -- 返回的模型的子级是数组而不是 Backbone.Collection

Backbone.Model save -- returned model's child is array not Backbone.Collection.

本文关键字:Backbone 数组 Collection 模型 Model save 返回      更新时间:2023-09-26

我有一个模型,看起来像:

var Playlist = Backbone.Model.extend({
    defaults: function() {
        return {
            id: null,
            items: new PlaylistItems()
        };
    }
});

其中 PlaylistItems 是 Backbone.Collection。

创建播放列表对象后,我调用保存。

playlist.save({}, {
    success: function(model, response, options) {
        console.log("model:", model, response, options);
    },
    error: function (error) {
        console.error(error);
    }
});

在这里,我的模型是一个 Backbone.Model 对象。但是,它的子项属于 Array 类型,而不是 Backbone.Collection。

这是意外的行为。我错过了什么吗?或者,我是否需要手动将数组传递到新的 Backbone.Collection 中并自行初始化?

这取决于您的服务器期望什么以及它响应什么。 Backbone 不知道属性items是 Backbone 集合以及如何处理它。 这样的东西可能会起作用,具体取决于您的服务器。

 var Playlist = Backbone.Model.extend({
    defaults: function() {
        return {
            id: null,
            items: new PlaylistItems()
        };
    },
    toJSON: function(){
        // return the json your server is expecting.
        var json = Backbone.Model.prototype.toJSON.call(this);
        json.items = this.get('items').toJSON();
        return json;
    },
    parse: function(data){
        // data comes from your server response
        // so here you need to call something like:
        this.get('items').reset(data.items);
        // then remove items from data: 
        delete data.items;
        return data;
    }
});