检测从集合主干中删除的模型

时间:2014-06-13 13:11:01

标签: javascript backbone.js backbone-views backbone-collections backbone-model

我目前正在开发一个骨干应用程序,而且我已经打了一点墙。我的收藏品看起来像这样,

    r {length: 3, models: Array[3], _byId: Object, constructor: function, model: function…}
_byId: Object
_events: Object
_listenerId: "l40"
length: 3
models: Array[3]
__proto__: s

正如您所看到的,该集合有3个模型,下面是该模型的一个示例,

    0: r
_changing: false
_events: Object
_pending: false
_previousAttributes: Object
attributes: Object
complete: false
completed_by: "0"
completed_by_name: null
end_date: false
files: r
id: "7693"
is_owner: false
item_active_task_count: 0
item_description: "sdsadasdasd"
item_files: r
item_id: "7693"
item_name: "First Item (1)"
item_tasks: r
item_type: null
numFile: 8
parent_id: null
progress: "0"
subItems: r
sub_items: Array[2]
tasks: r
__proto__: Object
changed: Object
cid: "c3"
collection: r
counter: 5
id: "7693"
__proto__: s

在上面的模型中我另一个名为item_files的集合,这个集合看起来像这样,

    _byId: Object
length: 8
models: Array[8]
0: r
1: r
2: r
3: r
4: r
5: r
6: r
7: r
length: 8
__proto__: Array[0]
__proto__: s

此集合中的模型如下所示,

    models: Array[8]
0: r
_changing: false
_events: Object
_listenerId: "l48"
_pending: false
_previousAttributes: Object
attributes: Object
creator: "Me"
creator_id: "14"
download_url: "http://test.dev/projects/download/696d6167655f31322e4a5047/698/14"
file_created: "2014-06-12 00:00:00"
file_hex: "696d6167655f31322e4a5047"
file_parent_id: "7694"
file_parent_type_id: "7694"
id: "9011"
is_owner: 1
last_modified: "2014-06-12 00:00:00"
panel_name: "image_12.JPG"
project_id: "698"
size: "1.76 MB"
thumb_url: null
timeago: "a day ago"
user_type: ""
viewer_url: "http://test.dev/projects/viewer/698/696d6167655f31322e4a5047"
__proto__: Object
changed: Object
cid: "c12"
collection: r
id: "9011"
__proto__: s

我目前正在做的是,正在开发一些删除功能,我有一个构建容器的函数,然后列出item_files集合中的模型,视图得到这样的构建,

addItems: function() {

    this.model.get('items').each(this.loadItem, this);

    //bind the expander
    $('.expander').unbind('click').click($.initExpanders.expander);


},

loadItem: function(item) {

    if(item.get("item_parent_id") == undefined) {
        var item_parent_id = item.get("item_id");
    }

    //item.set({"numFile" : item.get('item_files').length});

    var itemView = new app.ItemView({
        model: item,
        collection:item.get('item_files')
    });

    this.$el.find('.wrapper').append(itemView.render(item).el);
    if(item.get("subItems") !== undefined ) {
        if(item.get("subItems").length > 0) {
            if(item.get("subItems").length == 1) {
                this.$el.find(itemView.el).find('.sub-item-count').text(item.get("sub_items").length + " Sub Item"); 
            } else {
                this.$el.find(itemView.el).find('.sub-item-count').text(item.get("sub_items").length + " Sub Items");
            }
        }       
    }

    //itemView.addFilesWrapper(item);
    //itemView.addFiles();

    var itemFilesFilter = new app.FilesFilter({
        collection: item.get('item_files'),
        model: item
    });

    this.$el.find('article[data-item-id='+item.get('id')+'] .tab-content.files:first').html(itemFilesFilter.render().el);

    var that = this;
    item.get('files').each(function(file){
        var itemFileListItem = new app.FileListItem({
            model: file,
            collection: item.get('item_files'),
        });
        //console.log(that.$el.find('article[data-item-id='+item.get('id')+'] .tab-content').append(itemFileListItem.render().el));

        that.$el.find('article:first[data-item-id='+item.get('id')+'] .image-grid:first').append(itemFileListItem.render().el);
    });

},

所以上面列出了项目集合中的模型,我以为我能够收听项目集合进行更改,然后运行我需要的任何功能,因为更改包含并编辑添加或删除。

但是,如果我从集合中删除模型,则更改事件似乎不会触发什么问题?

1 个答案:

答案 0 :(得分:1)

如何从集合中删除模型? (抱歉会对此发表评论,但不要求代表) 编辑 -

这里有一个鼓泡停止的例子,在这个例子里我有一个城市(收藏)谁的模范城市有邻居(收藏)谁的模型neighbourhod有人(收藏)

可以通过人员集合检测到从邻居中删除某个人,但是没有任何进一步向上,这会稍微更新一下该事件如何被激活链

var NeighbourHoodModel = Backbone.Model.extend({
  defaults:{
    name: null,
    people:null
  }
});
var PeopleModel= Backbone.Model.extend({
  defaults:{
    name: null
  }
});
var CityModel = Backbone.Model.extend({
  defaults:{
    neighbourhoods:null
  }
});
var NeighborhoodsCollection = Backbone.Collection.extend({
  model: NeighbourHoodModel
});
var PeopleCollection = Backbone.Collection.extend({
  model: PeopleModel
});
var CityCollection = Backbone.Collection.extend({
  model: CityModel
})


var cities = new CityCollection([
  { id:1, neighbourhoods: new NeighborhoodsCollection([
      { id:1,name: "neighbourhood-1",
        people: new PeopleCollection([
          { id:1,name: "jim"},
          { id:2,name: "fred"}
         ])
      }

     ]),
  }
]);

(function(cities){


  cities.forEach(function(city){
   city.get("neighbourhoods").get(1).get("people").on("remove", function(){


    console.log("person removed")
   });
   city.get("neighbourhoods").get(1).on("remove", function(){
    console.log("person removed from neighbourhood")
   });

   city.get("neighbourhoods").on("remove", function(){
    console.log("person removed from neighbourhoods")
   });
   city.get("neighbourhoods").get(1).get("people").remove(1);


});

})(cities); 

2ND编辑 - 好的,想出了一种获取模型属性的方法,该模型属于集合的一部分以传递事件。所有你要传递这个和你想听的属性,然后它会听取该属性的删除,如果它也是一个集合的成员,它将为集合触发一个删除事件。然后它还会对属性上的更改事件进行修改,以便您知道该模型中的某些内容已更改。原始模型已删除,上下文也可用,就像使用普通删除事件一样

但是,这可能有点矫枉过正。

在笔视图((pen version of code))上查看控制台,您将看到人员移除事件已经传递到链上。你可以删除我刚刚传入的logMessage参数,这样你就可以看到它在控制台中工作了。

添加的函数_bubbleEventToCollection

Backbone.Model.prototype.bubbleEventToCollection = function(caller, model, logMessage){
            this.listenTo(model, "remove", function(model, that, options) {
                console.log(logMessage, model);
                if (this.collection instanceof Backbone.Collection) {
                    this.collection.trigger("remove", model, that, options);
                }
                this.trigger("change", model, that, options);
            }, caller);
    };
    var PeopleModel = Backbone.Model.extend({
        defaults: {
            name: null
        },
        initialize: function() {
            this.on("remove", function(model) {
                console.log("person removed", model)
            }, this);
        }
    });
    var NeighbourHoodModel = Backbone.Model.extend({
        defaults: {
            name: null,
            people: null
        },
        initialize: function() {
            this.bubbleEventToCollection(this, this.attributes.people, "person removed from neighbourhood");
        }
    });
    var CityModel = Backbone.Model.extend({
        defaults: {
            neighbourhoods: null
        },
        initialize: function() {
              this.bubbleEventToCollection(this, this.attributes.neighbourhoods, "person removed from city");
        }
    });


    /**
     *
     * Collections
     */
    var NeighborhoodsCollection = Backbone.Collection.extend({
        model: NeighbourHoodModel,
        initialize: function() {
            this.on("remove", function(model) {
                console.log("person removed from neighbourhoods", model)
            }, this);
        }

    });
    var PeopleCollection = Backbone.Collection.extend({
        model: PeopleModel,
        initialize: function() {
            this.on("remove", function(model) {
                console.log("person removed from people", model)
            }, this);
        }

    });
    var CityCollection = Backbone.Collection.extend({
        model: CityModel,
        initialize: function() {
            this.on("remove", function(model) {
                console.log("person removed from cities", model)
            }, this);
        }
    })


    var cities = new CityCollection([{
        id: 1,
        neighbourhoods: new NeighborhoodsCollection([{
                id: 1,
                name: "neighbourhood-1",
                people: new PeopleCollection(
                    [{
                        id: 1,
                        name: "jim"
                    }, {
                        id: 2,
                        name: "fred"
                    }])
            }

        ]),
    }]);

    (function(cities) {
        cities.get(1).get("neighbourhoods").get(1).get("people").remove(1);
    })(cities);