У меня есть RelationalModel "Todo", который "HasMany" комментирует (вложенный массив). Как удалить конкретный комментарий из этой вложенной коллекции? Было бы здорово, если бы кто-нибудь мог также привести примеры того, как добавить (и обновить) «комментарий» к этому вложенному массиву. это или это лучший способ сохранить всю коллекцию в локальном хранилище ? Почему из коробки нет возможности удалить элемент из вложенной коллекции и сохранить его?
Я пытался
эта.модель.уничтожить()
и
this.model.bind("уничтожить", this.remove)
внутри моего CommentView, но это удаляет комментарий только из DOM и из Backbone «CommentCollection», но не из локального хранилища. Итак, почему-то он не синхронизирует CommentCollection и localstorage.
Todos в localstorage выглядят так:
{"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()");
},
});
Комментарий:
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;
},
});