4

我有一个 RelationalModel “Todo”,其中“HasMany”注释(嵌套数组)。如何从此嵌套集合中删除特定评论?如果有人还可以提供如何向这个嵌套数组添加(和更新)“评论”的示例,那就太好了。这是整个集合保存在本地存储中的最佳方式吗?为什么没有现成的功能可以从嵌套集合中删除元素并保存它?

我试过了

this.model.destroy()

this.model.bind("销毁", this.remove)

在我的 CommentView 中,但这只会从 DOM 和主干“CommentCollection”中删除评论,而不是从本地存储中删除。所以,不知何故,它不会同步 CommentCollection 和本地存储。

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;
 },
});
4

0 回答 0