I have a RelationalModel "Todo" which "HasMany" comments (nested array). How do I remove a particular comment from this nested collection? It would be great if someone could provide also examples how to add (and update) a "comment" to this nested array. Is that or that the best way to save the entire collection in localstorage? Why is there no functionality out of the box to remove an element from a nested collection and save it?
I tried
this.model.destroy()
and
this.model.bind("destroy", this.remove)
inside my CommentView but this only removes the comment from the DOM and from the Backbone "CommentCollection", but not from the localstorage. So, somehow it doesn't sync the CommentCollection and localstorage.
Todos in localstorage look like this:
{"todo_1342290161303":{"content":"Hello Todo1","comments":[
{"id":"1","content":"Comment1","todo":"todo_1342290161303"},
{"id":"2","content":"Comment2","todo":"todo_1342290161303"}],"id":"todo_1342290161303"}
}
//-------------------- Comment MODEL ----------------
var Comment = Backbone.RelationalModel.extend({
idAttribute: "_id",
initialize: function() {
console.log("COMMENT MODEL: initialize()");
},
});
//-------------------- Comment Collection ----------------
var CommentCollection = Backbone.Collection.extend({
model: Comment,
localStorage: new Store("Todos-STORAGE-COMMENTS"),
initialize: function() {
console.log("COMMENT COLLECTION: initialize()");
//console.log(this.collection.get(1).get("content"));
}
});
//-------------------- Todo MODEL ----------------
var Todo = Backbone.RelationalModel.extend({
idAttribute: "id",
relations: [{
type: Backbone.HasMany,
key: "comments",
relatedModel: Comment,
collectionType: CommentCollection,
reverseRelation: {
key: "todo",
includeInJSON: "id",
},}],
initialize: function() {
console.log("--TODO MODEL: initialize()");
},
});
The CommentView:
var CommentView = Backbone.View.extend({
tagName: "li",
template: _.template($("#comment-template").html()),
events: {
"click span.delete-comment": "deleteComment"
},
initialize: function() {
_.bindAll(this, "render", "remove", "deleteComment");
this.model.bind("change", this.render);
this.model.bind("destroy", this.remove);
},
deleteComment: function(comment) {
this.model.destroy();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});