Backbone save without set on callback
I have a drag&drop functionality in my web app. As the user releases the mouse after a drag&drop, the position of the object is saved to the server using Backbone's save() method on the model. When the server responds, it triggers a set() on the model with the returned properties. However, in the time the server was processing the request, the user might already have again dragged the object to a different position. This causes problems as the response from the server will now override the settings of the object in the browser.
Is there a way to prevent Backbone from doing the set() after it gets the response from the server after the save()?
Had similar use case while doing a system before albeit that was more trouble hence we needed to really override the models set()
function. Although for this case a couple of relatively easier ways are available.
You can override the model parse() function. Or you can call an abort()
on the jqXHR object returned by the save()
call.
http://api.jquery.com/jQuery.ajax/#jqXHR
Look into the "wait" option, by default it should be set to false which means your model fields should be set immediately after calling save(). You can set {wait:true} to make backbone wait for the server reply before setting the updated model field values.
From your described behavior, it sounds like wait option is set to true in your application.
Further details: http://backbonejs.org/#Model-save
One other important thing to remember is backbone only sets the subset of updated fields you return from the called webservice, so if you don't return any none will be set.
Model.save
will call Model.parse
on the data received with the same options
argument before actually setting it.
You could call Model.save
with a custom flag (let's say position: true
) indicating that Model.parse
can discard what the server returns.
For example, assuming your coordinates are x
and y
var M = Backbone.Model.extend({
parse: function(data, options) {
if (options && options.position)
data = _.omit(data, 'x', 'y');
return data;
}
});
var m = new M();
m.save({x: 10, y:10}, {position: true});
m.save({x: 20, y:20}, {position: true});
And a demo http://jsfiddle.net/nikoshr/YwC7q/
链接地址: http://www.djcxy.com/p/67076.html上一篇: 保存后避免解析
下一篇: 骨干保存没有设置回调