[英]Why does Backbone.Model.fetch() return data in a wrapper?
Let's say I have a Backbone.js model: 假设我有一个Backbone.js模型:
// I declare it...
var Foo = Backbone.Model.extend({
url: '/resources/foo',
defaults: {
bar: true
}
});
// Construct it...
var foo = new Foo({});
// Locally set a value,
foo.set('floozy', true);
// And then fetch more data on it from the server.
foo.fetch();
Now say the server returns an object: 现在说服务器返回一个对象:
{
id: 1
bar: false,
floozy: false
}
If I inspect the model contents on fetch success, 如果我在获取成功时检查了模型内容,
foo.fetch({ success: function(){
console.log(this.toJSON());
}});
And inspect the model in firebug, the object looks like this: 并检查萤火虫中的模型,对象如下所示:
{
0: {
id: 1,
foo: false,
floozy: false,
},
foo: true,
floozy: true
}
In other words, instead of updating my existing values, it wraps the whole response in an unnamed object ( 0
). 换句话说,它没有更新我的现有值,而是将整个响应包装在一个未命名的对象(
0
)中。 I have not figured out why this is happening and I am stumped. 我还不知道为什么会这样,我很沮丧。 Why does this happen / what am I doing wrong?
为什么会这样/我在做什么错?
Your server is not returning what you think it is, it is returning an array with a single element like this: 您的服务器没有返回您所想的,而是返回了一个包含单个元素的数组,如下所示:
[{"id":1,"bar":false,"floozy":false}]
This part of your result is a dead give away: 结果的这一部分是致命的赠送:
0: { ... }
That looks like a single element array that has been interpreted as a simple key/value object. 看起来像一个元素数组,已被解释为简单的键/值对象。 I also know this because I can replicate your results at jsfiddle.net like this:
我也知道这一点,因为我可以像这样在jsfiddle.net复制您的结果:
var json = JSON.stringify([{id: 1, bar: false, floozy: false}]);
var M = Backbone.Model.extend({
url: '/echo/js?js=' + encodeURIComponent(json),
defaults: {
bar: true
}
});
var m = new M;
m.set('floozy', true);
m.fetch({
success: function(m) {
console.log(m.toJSON());
}
});
that results in the oddly familiar: 这导致了奇怪的熟悉:
0: Object
bar: false
floozy: false
id: 1
bar: true
floozy: true
in the console. 在控制台中。
Demo: http://jsfiddle.net/ambiguous/QF8ue/ 演示: http : //jsfiddle.net/ambiguous/QF8ue/
You can get around this by either fixing the server code or adding a parse
to your model: 您可以通过修复服务器代码或向模型添加
parse
来解决此问题:
parse: function(response) {
return _(response).isArray()
? response[0]
: response;
}
I threw in an _.isArray
call so that your model can work with both wrapped and unwrapped data. 我引发了一个
_.isArray
调用,以便您的模型可以同时处理已包装和未包装的数据。
Demo: http://jsfiddle.net/ambiguous/atSDp/ 演示: http : //jsfiddle.net/ambiguous/atSDp/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.