6

Backbone documentation says,

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.

But i have customized parse function for my model. I want to execute it only when i fetch data not when i save data.

Is there a way to do it? I can check my response inside parse function. But is there any built-in option to do it?

4

2 回答 2

7

这是来自关于保存模型的主干源文件:

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);
};

您可以在您的savelike:上传递一个自定义选项model.save(null, { saved: true }),然后在您的 custom 中parse

parse: function(response, options) {
    if ( options.saved ) return this.attributes;
    // do what you're already doing
}

我根本没有测试过这个,但它至少应该让你开始。

于 2013-08-27T04:49:33.730 回答
4

只需将 parse:false 作为选项传递给 save 方法。

m = new MyModel()
s.save(null, {parse: false})
于 2015-09-15T18:59:39.870 回答