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?
js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
There is only method named "start" can be used to manipulate the Backbone. js history.
Front-End MVC frameworks (Backbone, Angular, etc) all rely on a backend service to provide the data that, say Backbone, would then use as its model. You could have an entire MVC pattern on the backend that accepts requests and spits out some JSON for a frontend MVC framework to use.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With