Andrea
Andrea

Reputation: 20493

Backbone model validation

I have encountered a strange behaviour of the model validation in Backbone.js.

When a model is first created, like

var foo = new Foo({
    bar: 42
});

Backbone invokes foo.set() passing as a parameter the given map {bar: 42}, as one can see from the source. In doing so, it also passes the options {silent: true}, as in the line

this.set(attributes, {silent : true});

This makes sense, since having silent === true avoids triggering the change events, which do not make sense in this context.

For some reason I cannot understand, though, silent === true also prevents validation; see the source at the line

if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;

So it appears model are never validated when they are created, but they usually are when some attributes are changed. Moreover, the presence of the validation is inextricably tied to the action of sending change events, which is something completely orthogonal.

Can anyone explain why this is so? What would be a clean and future proof way to fix this issue?

I could manually call _performValidation, but this has two drawbacks:

Upvotes: 5

Views: 3065

Answers (2)

nourdine
nourdine

Reputation: 7597

as of now the only way to stay safe is to never pass in parameters hash.

I always do:

var m = new MyModel();
// and then I do all the sets
m.set(...);
m.set(...);
m.set(...);

In case some JSON data comes from the DB, then they are supposed to have been validated already and so in that case it's fine to:

var m = MyMOdel(hashFromDB);

Does that make sense?

Upvotes: 0

Atinux
Atinux

Reputation: 1703

Indeed I think that's a bug on Backbone.JS.

There is an open issue on GitHub here: https://github.com/documentcloud/backbone/issues/870

Edit : In the new version 0.9.1 of Backbone.js, you can test if the model is valid with isValid method ( http://backbonejs.org/#Model-isValid )

Upvotes: 3

Related Questions