5
My REST api returns data in json in following format for `/api/users`:

{
    "objects":[
        {"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"some.email@gmail.com","role":"admin"}},
        {"User":{"id":"2","created":"2013-02-13 09:22:55","modified":"2013-02-13 09:22:55","username":"some.email2@gmail.com","role":"analyst"}},
        {"User":{"id":"3","created":"2013-02-13 09:23:02","modified":"2013-02-13 09:23:02","username":"some.email3@gmail.com","role":"moderator"}},
        {"User":{"id":"4","created":"2013-02-13 09:23:10","modified":"2013-02-13 09:23:10","username":"some.email4@gmail.com","role":"representative"}}
        ],
    "meta":
        {"page":1,"pageCount":1,"prevPage":false,"nextPage":false,"limit":20,"count":4,"sort":null,"direction":null}
}

因为/api/users/{id}它以以下格式返回数据:

{"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"some.email@gmail.com","role":"admin"}

我如何将它与 Backbone.js 集合和模型集成?我知道 Backbone.js 期望 api 返回对象字典或纯对象字典的数组 - 有没有办法改变它?

4

1 回答 1

10

就在这里。您可以覆盖model.parsecollection.parse。例如:

var UserCollection = Backbone.Collection.extend({
                model: User, 
                url: '/api/users',
                parse: function(response) {
                        // process response.meta when necessary...
                        return response.objects;
                    });
                }
            });

var UserModel = Backbone.Model.extend({
                 //...
                 parse: function(response) {
                        return response.User;
                    });
                }
            });
于 2013-02-13T10:40:38.800 回答