Dealing with invalid data
If the data was stored within the database with an invalid state, you can either:
- Fix it manually from the server side with tools (like MySQL Workbench, etc.)
- Ensure dynamically in the backend that the data is valid before sending the response
- Make a
parse
function in your Backbone Model which handle the case you have right now
A simple parse function could look like:
var MyModel = Backbone.Model.extend({
/**
* Called with the raw response data
*/
parse: function(data, options) {
// fix the problem within the data object.
if (_.has(data, 'myAttribute')) {
data.myAttribute = /* correction here */
}
// return the fixed data object
return data;
}
});
Why the collection length is zero?
It's because the collection sends the received data (locally as a param or following a fetch) to its private _prepareModel
method which ensure that the data is a valid Backbone Model.
_prepareModel: function(attrs, options) {
if (this._isModel(attrs)) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options = options ? _.clone(options) : {};
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
It returns the model only if validationError
is falsy (null
by default and thruty whenever a validation rule returned an error message string or array).
if (!model.validationError) return model;
Otherwise, it returns false and doesn't add the model to the collection.