BackboneJS和JSON-api wordpress(访问模型的子对象)

时间:2013-06-23 14:47:42

标签: json backbone.js

[编辑] 已回答 [/编辑]

我刚开始使用Backbone,遇到了一个我无法弄清楚的绊脚石。

我有以下集合,它在我的网站上向JSON-API发送请求以按类别提取帖子:

Posts.Collections.CategoryPosts = Backbone.Collection.extend({

initialize: function(options) {
    this.id = options.id;

    var intRegex = /^\d+$/;

    if(intRegex.test(this.id)) {
        this.url_querystring = '?id=' + this.id;
    }
    else {
        this.url_querystring = '?slug=' + this.id;
    }
},

url: function() {
    return '/api/core/get_category_posts/' + this.url_querystring;
},

model: Posts.Models.CategoryPost
});

现在,这有魅力;但问题是;此返回的JSON实际上是:

{
    "status": "ok",
    "count": 10,
    "count_total": 79,
    "pages": 7,
    "category": { ... }
    "posts": [
        { ... },
        { ... },
    ...
    ]
}

因此,当我在集合上使用fetch()的代码尝试将返回值分配给各个Post模型时;它只创造一个。

如何告诉Backbone应该使用JSON返回中的“post”子对象创建模型?那里似乎没有很多关于这一点;或者我不确切地知道要搜索什么?

任何帮助都会很棒 - 最好是朝着正确的方向努力,而不是给出答案。

1 个答案:

答案 0 :(得分:2)

答案是为集合定义一个解析函数:

Posts.Collections.CategoryPosts = Backbone.Collection.extend({

    initialize: function(options) {
        this.id = options.id;

        var intRegex = /^\d+$/;

        if(intRegex.test(this.id)) {
            this.url_querystring = '?id=' + this.id;
        }
        else {
            this.url_querystring = '?slug=' + this.id;
        }
    },

    // Make sure you parse the correct JSON object!
    parse: function(response) {
        return response.posts;
    },

    url: function() {
        return '/api/core/get_category_posts/' + this.url_querystring;
    },

    model: Posts.Models.CategoryPost
});