问题描述
我有一个骨干模型:
var User = Backbone.Model.extend({
idAttribute: '_id',
url: '/api/user',
defaults:
{ username: ''
}
});
我把它拿来:
var user = new User();
user.fetch();
现在,在我的观点之一的点击
事件,我有这样的:
Now, as an click
event in one of my views, I have this:
toggleSubscription: function () {
user.set('subscriptions', true);
user.save();
}
这会导致一个POST请求。然而,记录已经存在服务器上,因为我取它(和模型实例有一个 ID
属性),我以为骨干应该做的PUT而不是POST。为什么会它做一个POST呢?
This causes a POST request. However, the record already exists on the server, and since I fetched it (and the model instance has an id
property), I thought that Backbone should do a PUT instead of a POST. Why might it be doing a POST instead?
推荐答案
尝试检查 user.isNew()
。
看起来你创建了没有ID的新模式,这是在为什么它试图将其添加Backbone.sync
。
Looks like you created a new model which does not have an ID, that's why it's trying to add it during Backbone.sync
.
更新:
以上是完全正确的。它确实 POST
,因为它是一个新的模式(这意味着,它没有一个id)。在你取一个模式,你需要给它一个ID。在您的例子:
Above is exactly true. It does POST
because it's a new model (which means, it does not have an id). Before you fetch a model, you need to give it an id. In your example:
var user = new User();
user.fetch();
user.save(); // in XHR console you see POST
var user = new User({ id: 123 });
user.fetch();
user.save(); // in XHR console you see PUT
这篇关于骨干model.save()导致POST不把的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!