model.save()的Backbone.js / express.js参数 [英] Backbone.js/express.js parameters for model.save()
问题描述
我在客户机上使用Backbone.js,在后端使用node.js,并且在限制模式保存时遇到麻烦,如下所述: http://backbonejs.org/#Model-save
I'm using Backbone.js on the client and node.js on the backend, and I'm having a bit of trouble doing a 'limited' model save, as explained here : http://backbonejs.org/#Model-save
如例如,如果我执行
book.save({author: "Teddy"});
如何使用express.js访问保存的参数,即我只想要保存到作者字段?我尝试了以下
how do I access the parameters of the save using express.js, i.e. the fact that I only want to save to the 'author' field? I've tried the following
req.body -> gives ALL parameters of the model being saved, I want only the 'author' field
req.query -> empty
任何帮助非常感谢!
推荐答案
如 Model.save文档:
保存属性],[选项])
[...]属性哈希(如集合中)应包含要更改的属性 -
键,提到的提示不会被更改 - 但是,完整的
表示资源将被发送到服务器。
save model.save([attributes], [options])
[...] The attributes hash (as in set) should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server.
但是,您可以覆盖保存方法,并通过将发送到服务器的选项提供数据
属性,而不是完整的模型表示。例如,这将只保存传递给方法的属性:
You can however override the save method and provide a data
attribute via the options which will be sent to the server instead of the full model representation. For example, this will only save the attributes passed to the method :
var M = Backbone.Model.extend({
save: function (attrs, options) {
options || (options = {});
options.contentType = 'application/json';
options.data = JSON.stringify(attrs);
Backbone.Model.prototype.save.call(this, attrs, options);
}
});
和小提琴 http://jsfiddle.net/dLFgD/
正如@mikebridge所说注释,现在可以通过传递 attrs
选项来获取此行为。所以要么使用
As @mikebridge noted in the comments, this behavior can now be obtained by passing an attrs
option. So either use
book.save(null, {
attrs: {author: "Teddy"}
});
或保留覆盖
var M = Backbone.Model.extend({
url: '/echo/json/',
save: function(attrs, options) {
options || (options = {});
options.attrs = attrs;
Backbone.Model.prototype.save.call(this, attrs, options);
}
});
http://jsfiddle.net/nikoshr/dLFgD/7/
如果您使用支持它的Backbone版本(> = 0.9.9),并且您的服务器了解该动词,您也可以发送PATCH请求,如
You could also send a PATCH request if you're using a Backbone version that supports it (>=0.9.9) and your server understands that verb, as explained in @pkyeck's answer
这篇关于model.save()的Backbone.js / express.js参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!