backbone icon indicating copy to clipboard operation
backbone copied to clipboard

Parse model before validating on model.set(pojo, {parse:true})

Open maxponte opened this issue 11 years ago • 1 comments

If I have a Backbone model that expects a wrapped object from the API e.g. {a: {a: 3}}

But I want to work with it as {a:3}

It is nice to use parse like

parse: function(data) {
  return data.a;
}

And validate like

validate: function(attrs) {
  if(!_.has(attrs, 'a') || !_.isNumber(attrs.a)) {
    return 'incorrect signature';
  }
}

And when I mock out the model in a test I do:

model.set({a: {a:3}}, {parse: true})

But this fails because model.set calls validate before parsing my object. This doesn't make a whole lot of sense to me. If I say {parse: true} it should parse before validating. My workaround is

var o = {a: {a:3}};
model.set(model.parse(o));

But I feel like it would be less confusing to have {parse: true} actually work as expected when you have a validate function.

maxponte avatar Aug 13 '15 20:08 maxponte

Model#set doesn't have a parse option. I think you're thinking of Colleciton#set which (sadly) does, but that'll be gone in v2.

See #3644's OP for reasoning.

jridgewell avatar Aug 13 '15 20:08 jridgewell