app/assets/javascripts/backbone-nested-attributes/model.js in backbone-nested-attributes-0.2.3 vs app/assets/javascripts/backbone-nested-attributes/model.js in backbone-nested-attributes-0.3.0

- old
+ new

@@ -33,26 +33,38 @@ } function setNestedAttributeFor(model, relation, attributes) { var key = relation.key, value = attributes[key], + deletedValue = attributes['deleted_' + key], currentValue = model.get(key), nested = currentValue || createNestedAttributeCollection(relation) - value = value instanceof Backbone.Collection ? value.slice() : value + value = valueOrSliceCollection(value) configureEventBubbling(model, nested, relation) if (value) { nested.set(value) } + if (deletedValue) { + delete attributes['deleted_' + key] + + deletedValue = valueOrSliceCollection(deletedValue) + nested.deletedModels.set(deletedValue) + } + attributes[key] = nested return attributes } + function valueOrSliceCollection(value) { + return value instanceof Backbone.Collection ? value.slice() : value + } + function clearDeletedModelsFor(model) { _(model.relations).each(function (relation) { var collection = model.get(relation.key) collection.each(function (nestedModel) { @@ -99,16 +111,24 @@ value = json[key], deleted = [], jsonValue if (value) { - if (options && options.nested) { - delete json[key] - key = key + '_attributes' + if (options) { + if (options.withDeleted) { + if (value.deletedModels) { + json['deleted_' + key] = value.deletedModels.toJSON(options) + } + } - if (value.deletedModels) { - deleted = value.deletedModels.toJSON(options) + if (options.nested) { + if (value.deletedModels) { + deleted = value.deletedModels.toJSON(options) + } + + delete json[key] + key = key + '_attributes' } } jsonValue = value.toJSON(options) @@ -128,18 +148,19 @@ collection = new CollectionType collection.model = _(relation).result('relatedModel') || collection.model collection.deletedModels = new Backbone.Collection - collection.on('remove', nestedModelRemoved, collection) + collection.deletedModels.model = collection.model + collection.on('remove', nestedModelRemoved) return collection } - function nestedModelRemoved(model) { + function nestedModelRemoved(model, collection) { if (!model.isNew()) { model.set({ _destroy: true }) - this.deletedModels.add(model) // this refers to the collection + collection.deletedModels.add(model) } } function attributesFor(key, value, options) { var attributes \ No newline at end of file