从backbone.js集合中获取JSON对象
我从 RESTful API 获取 JSON 提要。我从服务器获得的 JSON 是一个包含 2 个不同对象数组的对象。我将该 JSON 分解为几个不同的 Backbone 集合,效果很好。我的主干对象看起来像这样:
Document = Backbone.Model.extend({
defaults:{
did: '',
fields: []
}
});
Documents = Backbone.Collection.extend({
model: Document
});
对象本身很好,但我尝试使用 Handlebars.js 进行模板化,并发现必须采用对象,而不是数组。当我获取 Documents 对象并执行 .toJSON() 时,它似乎返回一个数组,而不是一个对象。所以我从服务器获得的原始 JSON 看起来像:
{
"Docs":[
{"Fields":[{"ID":59,"VAL":""},{"ID":157,"VAL":""}],"Id":4143},
{"Fields":[{"ID":59,"VAL":""},{"ID":69,"VAL":""}],"Id":4142}
]
}
但是一旦它被推入主干集合然后拉回以进行车把交接,它看起来像这样:
[
{"Fields":[{"ID":59,"VAL":""},{"ID":157,"VAL":""}],"Id":4143},
{"Fields":[{"ID":59,"VAL":""},{"ID":69,"VAL":""}],"Id":4142}
]
我怎样才能让主干给我返回对象而不仅仅是一个包含对象内容的数组?
I am geting a JSON feed from a RESTful API. The JSON I get from the server is an object with 2 different arrays of objects. I am breaking that JSON into a couple different Backbone collections which works fine. My backbone objects looks like this:
Document = Backbone.Model.extend({
defaults:{
did: '',
fields: []
}
});
Documents = Backbone.Collection.extend({
model: Document
});
The objects themselves are fine, but I am trying to use Handlebars.js for templating and have found the must take an object, not an array. When I take my Documents object and do a .toJSON(), it seems to return an Array, not an object. So the raw JSON i get from the server looks like:
{
"Docs":[
{"Fields":[{"ID":59,"VAL":""},{"ID":157,"VAL":""}],"Id":4143},
{"Fields":[{"ID":59,"VAL":""},{"ID":69,"VAL":""}],"Id":4142}
]
}
But once it gets pushed into the backbone collection then pulled back out for the handlebars handoff, it looks like this:
[
{"Fields":[{"ID":59,"VAL":""},{"ID":157,"VAL":""}],"Id":4143},
{"Fields":[{"ID":59,"VAL":""},{"ID":69,"VAL":""}],"Id":4142}
]
How can I get backbone to give me back the object rather than just an array with the contents of the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
backbone 为您提供集合中的数组,因为这就是集合所保存的内容——模型数组。
我不确定我是否清楚您要做什么,但看起来您真正需要的只是让服务器接收一个如下所示的文档:
如果是这种情况,我只需覆盖您的 Documents 类上的 toJSON 方法可以执行以下操作:
这应该几乎可以满足您的要求,至少按照我的理解。
backbone gives you an array from a collection because that is what the collection holds -- an array of models.
I'm not sure I'm clear on exactly what you're trying to do, but it looks like all you actually need is to have the server receive a document that looks like:
If this is the case, I'd just override the toJSON method on your Documents class to do something like:
This should pretty much do what you say you want, at least as I understand it.
不幸的是,Backbone 系列在车把上的表现不如其应有的效果。由于它返回一个普通的 JavaScript 对象,因此您必须这样引用它。
尝试:
Unfortunately Backbone collections don't play as nicely as they should with handlebars. Since it returns a plain JavaScript object you have to reference it as such.
Try: