如何在 Backbone 模型中处理自定义响应 [英] How to handle custom response in Backbone model

查看:24
本文介绍了如何在 Backbone 模型中处理自定义响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在我的项目中集成主干.我遇到的第一个困难是来自后端的响应不是 JSON 数组或不是为主干设计的.这是一个例子.

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'
});

所以考虑一下,当我请求/people 时,它​​不会返回人的 JSON 数组.相反,它返回如下内容:

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" }

它的问题是主干无法将此 JSON 响应分配给模型.是否可以在控制器中对响应进行任何调整.所以访问模型可以正常.任何前/后挂钩.

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.

仅供参考:主干正在从服务器获得响应,我可以在responseText"键下看到它.

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

非常感谢任何帮助.

推荐答案

Backbone 支持这一点.当使用来自 Parse.com 的数据时,我遇到了同样的问题.在您的情况下,当您有一个不返回数组的 /people 端点时,您可以覆盖 Collection.parse 函数以向 Backbone 展示如何找到它所在的数组寻找:

Backbone supports this. I ran into the same issue when consuming data from Parse.com. 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;
  }
});

如果您需要在此功能中执行更多操作,那么您应该这样做.以类似的方式,您可以根据需要覆盖 Model.sync.

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.

这篇关于如何在 Backbone 模型中处理自定义响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆