C
C
Cat Anton2014-10-15 00:56:03
JavaScript
Cat Anton, 2014-10-15 00:56:03

How to forbid adding objects to a collection if there are already similar objects in it?

How can a collection ignore attempts to add a model to it that has a certain attribute whose value matches one of the ones in the collection, only if the {merge: true} option is not passed?
Example:

var Model = Backbone.Model.extend({
    defaults: {
        prop: null,
    }
});
var Collection = Backbone.Collection.extend({
    model: Modal
});

var test = new Collection([{prop: "A"}, {prop: "B"}, {prop: "A"}]); 
// В коллекцию попадут только 2 объекта: {prop: "A"} и {prop: "B"}

test.add({prop: "B"}); // в коллекцию ничего не добавится
test.add({prop: "B"}, {merge: true}); // в коллекцию добавится ещё один {prop: "B"}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Melnikov, 2014-10-15
@27cm

you can try
jsbin.com/buzoqu/1/edit?js,output like this
but it would probably be more correct like this
jsbin.com/sohuq/3/edit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question