Reputation: 1945
I want my model to validate for duplicate entry, so I need to access the collection while in the model.
I'm using Backbone.JS together with Require.JS and this makes it a little more confusing. I can't seem to load my collection as a dependency for the module.
I tried doing validation in the view, but I guess the best practice would be to keep validation in the model where it should be.
Any advice?
Upvotes: 2
Views: 91
Reputation: 18566
From Backbone Collection docs:
If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true} ...
Which in the add
-method translates to this:
if (existing = this.get(model)) {
if (options.merge) {
existing.set(attrs === model ? model.attributes : attrs, options);
if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true;
}
continue;
}
Basically that will trump adding any model with duplicate id
, cid
or idAttribute
.
If that isn't enough, then I suggest you do the validation in the view, because bringing a model's collection as a dependency to that exact model would introduce a circular dependency, eg. you need the collection to be able to compile the model, but you also need the model to compile the collection.
So if you need to make sure you're not adding a model to a collection with exactly the same attributes as a model already in that collection, do it in the view. It would look something like this:
if (collection.where(modelToBeAdded.toJSON()).length == 0) {
collection.add(modelToBeAdded);
}
Upvotes: 2