【问题标题】:Backbone Model/Collection fetch does not store the result骨干模型/集合提取不存储结果
【发布时间】:2014-04-03 06:04:20
【问题描述】:

又是一个有趣的 Backbone.js 问题。

当我调用Model#fetch()Collection#fetch() 时,Backbone 将正确调用服务器,但它不会存储结果,但会按预期保存。

在我发现的每个教程中,他们都解释说模型将存储在 fetch() 之后。

示例

响应包含“成功”并且集合包含具有正确 json 的 XHR 对象

tagCollection = new CategoryCollection();

tagCollection.fetch({
    complete: function(collection, response) {
        console.log(tagCollection.models);
    },
});

代码

/models/category.js

define(['underscore', 'backbone'], function(_, Backbone){

    var CategoryModel = Backbone.Model.extend({
        urlRoot: '/api/v1/category',
    });

    return CategoryModel
});

/collections/category.js

define(['underscore', 'backbone', 'categoryModel'], function(_, Backbone, CategoryModel){

    var CategoryCollection = Backbone.Collection.extend({
        model: CategoryModel,
        url: '/api/v1/category'
    });

    return CategoryCollection
});

/api/v1/category(.json)

[
    {
        id: "1",
        name: "Allgemeines",
        deleted_at: null,
        created_at: "2014-02-23 17:22:22",
        updated_at: "2014-02-23 17:22:22"
    }
]

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    Fetch 接受“成功”回调而不是“完成”回调。假设数据从服务器成功地从主干传来,它可能只是没有注销,因为回调没有触发。试试这个:

    tagCollection.fetch({
        success: function(collection, response) {
            console.log(tagCollection.toJSON());
        },
    });
    

    【讨论】:

    • 回调正在触发,成功不会触发(错误或失败都不会)。
    • 您能否在完整的回调中添加从“响应”返回的内容?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多