Backbone.js的为model.save / EX press.js参数() [英] Backbone.js/express.js parameters for model.save()

查看:205
本文介绍了Backbone.js的为model.save / EX press.js参数()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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"});

我怎么访问的参数保存使用前press.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

任何帮助非常AP preciated!

Any help much appreciated!

推荐答案

Model.save文档中所述

保存 model.save([属性],[选项])的结果
  [...]属性的散列(如设置)应包含你想改变属性 -
  未提及键不会改变 - 但是,一个完成
  再资源的presentation 将被发送到服务器。

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.

但是,您可以覆盖保存方式,通过将被发送到服务器,而不是完整的模型重新presentation的选项提供了一个数据属性。例如,这将只保存传递给该方法的属性:

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/

您还可以,如果您使用的是支持它的主干版本(> = 0.9.9)发送PATCH请求和服务器理解动词,为的在@ pkyeck的回答解释

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

这篇关于Backbone.js的为model.save / EX press.js参数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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