Backbone-relational:从localstorage中删除嵌套数组属性的元素

时间:2012-07-14 18:54:30

标签: backbone.js backbone-relational

我有一个RelationalModel“Todo”,其中“HasMany”注释(嵌套数组)。如何从此嵌套集合中删除特定注释?如果有人能提供如何向这个嵌套数组添加(和更新)“注释”的示例,那将是很棒的。 thatthat是将整个集合保存在localstorage中的最佳方法吗?为什么没有开箱即用的功能从嵌套集合中删除元素并保存它?

我试过

  

this.model.destroy()

  

this.model.bind(“destroy”,this.remove)

在我的CommentView中,但这只会从DOM和Backbone“CommentCollection”中删除注释,但不会从localstorage中删除。因此,它不会同步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()");
        }, 
  }); 

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

0 个答案:

没有答案