I would like to make sure that a specific attribute is unique across the collection when a new model is created so that I can ultimately use this attribute as a permalink.
I have a List Collection and List Model. (CoffeeScript)
class App.Models.List extends Backbone.Model
defaults:
name: "My New List"
class App.Collections.ListSet extends Backbone.Model
model: App.Models.List
When a new model is added to the ListSet, I would like to add a auto-incrementing number to the end of the name attribute if a model exists with that name already. For example My New List 1 if a model existed with My New List.
I don’t want it to be obtrusive and show an error, but just fix the problem automatically. I am happy with the logic behind adding the incrementing integer, but I need direction on where to put the code to make the changes.
This might work for you:
Here’s a demo: jsFiddle DEMO
What this should do is every time you initialize a model, you scan your collection to see if any other models have that same
originalName. If so, you tack on the result to the name attribute.=== UPDATE ===
I realize now that it’s probably better to do the modification when the model is added to the collection, so as to decouple the model from the collection. Here’s an updated code snippet:
and a demo: jsFiddle DEMO