Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom REST api response in Backbone.js

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":"[email protected]","role":"admin"}},
        {"User":{"id":"2","created":"2013-02-13 09:22:55","modified":"2013-02-13 09:22:55","username":"[email protected]","role":"analyst"}},
        {"User":{"id":"3","created":"2013-02-13 09:23:02","modified":"2013-02-13 09:23:02","username":"[email protected]","role":"moderator"}},
        {"User":{"id":"4","created":"2013-02-13 09:23:10","modified":"2013-02-13 09:23:10","username":"[email protected]","role":"representative"}}
        ],
    "meta":
        {"page":1,"pageCount":1,"prevPage":false,"nextPage":false,"limit":20,"count":4,"sort":null,"direction":null}
}

For /api/users/{id} it returns data in following format:

{"User":{"id":"1","created":"2013-02-13 09:22:42","modified":"2013-02-13 09:22:42","username":"[email protected]","role":"admin"}

How I can integrate this with Backbone.js Collection and Model? I know Backbone.js expects api to return array of object dicts or pure object dict - is there a way to change it?

like image 275
user606521 Avatar asked Feb 13 '13 10:02

user606521


1 Answers

Yes, there is. You could override model.parse or collection.parse. For example:

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;
                    });
                }
            });
like image 187
Hui Zheng Avatar answered Oct 24 '22 01:10

Hui Zheng