最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to handle custom response in Backbone model - Stack Overflow

programmeradmin0浏览0评论

I started integrating backbone in my project. The very first difficulty that i had was response from backend was not JSON Array or not designed for backbone. Here is an example.

//A backbone model
var Person = Backbone.Model.extend({});

// A backbone collection
var PersonCollection = Backbone.Collection.extend({  
  model : Person,  
  url: '/people'
});

So consider this, that when I request /people it does not return JSON array of people. Instead it return something like:

{header: "some str", people: ["person", "array", ".."], stats: "something is here" }

The problem with it is backbone is unable to assign this JSON response to models. Is there any tweak that can be done in controller on response. So accessing model can be normal. Any before/after hook.

FYI: backbone is getting response from server, I can see it under "responseText" key.

Any help is highly appreciated.

I started integrating backbone in my project. The very first difficulty that i had was response from backend was not JSON Array or not designed for backbone. Here is an example.

//A backbone model
var Person = Backbone.Model.extend({});

// A backbone collection
var PersonCollection = Backbone.Collection.extend({  
  model : Person,  
  url: '/people'
});

So consider this, that when I request /people it does not return JSON array of people. Instead it return something like:

{header: "some str", people: ["person", "array", ".."], stats: "something is here" }

The problem with it is backbone is unable to assign this JSON response to models. Is there any tweak that can be done in controller on response. So accessing model can be normal. Any before/after hook.

FYI: backbone is getting response from server, I can see it under "responseText" key.

Any help is highly appreciated.

Share Improve this question edited Jan 30, 2012 at 10:46 Darin Dimitrov 1.0m275 gold badges3.3k silver badges2.9k bronze badges asked Jan 30, 2012 at 10:41 ducktypedducktyped 4,5024 gold badges28 silver badges39 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Backbone supports this. I ran into the same issue when consuming data from Parse.. In your case, when you have a /people endpoint that does not return an array, you can override the Collection.parse function to show Backbone how to find the array it is looking for:

var PersonCollection = Backbone.Collection.extend({
  model : Person,
  url: '/people',
  parse: function(resp, xhr) {
    this.header = resp.header;
    this.stats = resp.stats;
    return resp.people;
  }
});

If you need to do more in this function, then you should. In a similar way, you can override Model.sync if you need to.

发布评论

评论列表(0)

  1. 暂无评论