zack
zack

Reputation: 3198

backbone-js: how can I silently initialize a new Collection?

I must be doing something dumb, or maybe missing some crucial part of the Backbone documentation, but I cant understand why the Model.validate function is firing when I initialize a new Collection in this way: http://jsfiddle.net/5a3k/QSeH6/ ..any ideas where I'm going wrong?

edit: changed title

Upvotes: 1

Views: 2444

Answers (1)

kubetz
kubetz

Reputation: 8556

By executing this line:

var myCollection = new Collection([{id: 'smith'}]);

You create new collection with one model. All models passed in the constructor will be added into the collection. Each added model is validated.

Details:

  1. Backbone.Collection constructor is calling this.reset() (source).
  2. .reset() will silently add all the models into the collection (source).
  3. .add() will call internal ._add() for each model (source).
  4. Internal ._add() will call .prepareModel which is checking if the model is valid (source).

Update (based on edit in the question):

model.validate is executed only if the model is not instance of Backbone.Model (source).

So if you create a collection using

var myCollection = new Collection([{id: 'smith'}]);

then the model is instance of Object. But if you use:

var myCollection = new Collection([ new Model({id: 'smith'}) ]);

then the model is instance of Backbone.Model and validation is skipped.

Upvotes: 4

Related Questions