parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
但是我为我的模型定制了解析函数。我只想在获取数据时执行它,而不是在保存数据时执行它。
有办法吗?我可以在解析函数中检查我的响应。但是有没有内置选项可以做到这一点?
最佳答案
这是来自主干source file关于保存模型:
var model = this;
var success = options.success;
options.success = function(resp) {
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
您可以在save
上传递自定义选项,例如:model.save(null, { saving: true })
,然后在您的自定义parse
:
parse: function(response, options) {
if ( options.saved ) return this.attributes;
// do what you're already doing
}
我根本没有测试过这个,但它至少应该让你开始。
关于backbone.js - Backbonejs - 保存后避免解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18457090/