resthub/resthub-backbone-stack — pull request #44 by bmeurant (2012-09-06 22:25:09+00:00)
Title: populateModel globally

old populateModel implementation performed one by one model assignation by calling set method for each form field.

new one set all attributes globally to fix a problem on validation that could lead to validate an invalid model.

An example will help to understand :

Let's imagine that we have a form with two fields firstname & lastname and a model with Backbone Validation with both firstname and lastname attributes required.

1. If, on form validation (with empty form), we call model.set one by one, two validation errors will be displayed.
2. If we change firstname to `test` and submit again, we will get only validation error for lastname
3. If we set firstname to "" again and validate the form, we will get only validation error for lastname !!!

This is because, on set, backbone call validate with a hash of attributes that is a merge of modified attributes with existing model attributes.

So when calling ``set('firstname', '')`` backbone display an error on firstname, as expected. But immediately after, we call ``set('lastname', '')`` backbone will merge firstanme new value with firstname old value stored in model. And, because, the invalid value '' was never stored, the valid 'test' value is taken !!!

To fix that point, ``populateModel`` set all model attributes in one operation building an attribute hash and calling ``set(attributes)``.

To validate fields one by one, just call ``validate()`` that triggers correctly but does not produce this side effect.