Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbonejs - Avoid parse after save

Tags:

backbone.js

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?

like image 869
user10 Avatar asked Aug 27 '13 04:08

user10


2 Answers

This is from the backbone source file regarding saving a model:

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

You could pass a custom option on your save like: model.save(null, { saved: true }), then in your custom parse:

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

I haven't tested this at all, but it should at least get you started.

like image 119
kalley Avatar answered Sep 24 '22 03:09

kalley


Just pass a parse:false into the save method as an option.

m = new MyModel()
s.save(null, {parse: false})
like image 24
stebooks Avatar answered Sep 20 '22 03:09

stebooks