「HasMany」コメント(ネストされた配列)のRelationalModel「Todo」があります。このネストされたコレクションから特定のコメントを削除するにはどうすればよいですか? このネストされた配列に「コメント」を追加 (および更新) する方法の例も誰かが提供できれば素晴らしいことです。コレクション全体をローカルストレージに保存する最良の方法はそれですか? ネストされたコレクションから要素を削除して保存するためのすぐに使える機能がないのはなぜですか?
私は試した
this.model.destroy()
と
this.model.bind("破棄", this.remove)
私のCommentView内ですが、これはDOMとバックボーンの「CommentCollection」からコメントを削除するだけで、ローカルストレージからは削除しません。そのため、どういうわけか、CommentCollection と localstorage が同期されません。
localstorage の Todo は次のようになります。
{"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;
},
});