简体   繁体   中英

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. First is a hash of properties, and the second are options (like the success and error callback). 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

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/

To avoid passing the success callback as an option, you can

  • use the promise returned by save :

     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. So...

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

Nice and neat...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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