简体   繁体   中英

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:

  • first, it is something I could simply forget
  • second, _performValidation is not part of the API and maybe it will change in future releases.

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 )

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM