简体   繁体   English

如何使用backbone.js保存而不指定哪些属性但使用回调

[英]How to save with backbone.js without specifying which attributes but with a callback

I'd like to save an altered model to the database (set before). 我想将修改后的模型保存到数据库中(之前设置)。 If the save succeeded redirect to another page (as example, could be any other action). 如果保存成功重定向到另一个页面(例如,可以是任何其他操作)。

Model.save can have two optional properties. Model.save可以有两个可选属性。 First is a hash of properties, and the second are options (like the success and error callback). 第一个是属性的哈希,第二个是选项(如成功和错误回调)。 http://backbonejs.org/#Model-save http://backbonejs.org/#Model-save

 somemodel.set({foo: 'bar'});
//lots of other logic and misc steps the user has to do
 somemodel.save(); //on success should go here

Since the attributes are already set, I only need the callback. 由于属性已经设置,我只需要回调。

In the past I did: 过去我做过:

somemodel.save(somemodel.toJSON(), { 
    success: function() { 
        //other stuff
    }
);

or passing the values again to the save method 或者将值再次传递给save方法

somemodel.save(
    { foo: this.$('input').val()}, 
    { success: function(){}
);

I'm looking for a way to clean this up. 我正在寻找一种方法来清理它。 The documents state, the model will fire a change state if there are new properties. 文档说明,如果有新属性,模型将触发更改状态。 But I'd want to redirect the user anyway (saving on new content or old/unaltered). 但是我想要重定向用户(保存新内容或旧/未更改)。

this does not exist: 这不存在:

somemodel.on('success', function(){}); 

and this, is only for validation: 而这只是用于验证:

if(somemodel.save()) { //action }

also "sync" is the wrong event (since it also works for destroy) “同步”也是错误的事件(因为它也适用于销毁)

Any help? 有帮助吗?

somemodel.save(
    {}, // or null
    { 
            success: function(){}
    }
);

will let you save a model with a specific callback without modifying existing keys. 将允许您使用特定回调保存模型,而无需修改现有密钥。

And a Fiddle http://jsfiddle.net/h5ncaayu/ 还有一个小提琴http://jsfiddle.net/h5ncaayu/

To avoid passing the success callback as an option, you can 为避免将成功回调作为选项传递,您可以

  • use the promise returned by save : 使用save返回的promise:

     somemodel.save().then(...youcallback...) 
  • or use an event : 或使用活动:

     somemodel.on('sync', ...youcallback...); somemodel.save(); 

Backbone.Model has a very convenient method called "changedAttributes" that will return a hash of changed attributes that you can pass to save. Backbone.Model有一个非常方便的方法叫做“changedAttributes”,它将返回一个可以传递给保存的已更改属性的哈希值。 So... 所以...

model.save(
   model.changedAttributes(),
   {
       success : _.bind(function() {...},this), //_.bind() will give scope to current "this"
       error : _.bind(function() {...},this);
   }
);

Nice and neat... 漂亮又整洁......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM