Backbone ListView创建僵尸

时间:2013-11-06 19:40:48

标签: listview backbone.js views zombie-process

我正在尝试使用项目视图和包含该项目视图的listView构建一个简单的crud应用程序,该视图是从集合构建的。我想为一个特定的项目有一个detailView,但是当切换到这个detailView时,我不知道如何正确处理listView。我已经看到了在单个视图中删除僵尸的解决方案,但没有看到由集合组成的视图。有没有直接的方法来清理由视图组成的List视图?

var Model = Backbone.Model.extend({
defaults : {
    id : '',
    name : ''
}

});
var Collection = Backbone.Collection.extend({
model : Model
})
var HomeView = Backbone.View.extend({
tagName : "div",
id : "home-view",
initialize : function() {
    $("body").html(this.el);
    this.render();
},
render : function() {
    this.$el.html("<h1>This is the home page</h1><a href='#users'>Go to users</a>");
}
});

var UserView = Backbone.View.extend({
tagName : "li",
initialize : function(e) {

    _.bindAll(this, "alertName");
    this.render();
},
events : {
    "click" : "alertName"
},
render : function() {
    this.$el.html("Hi, my name is " + this.model.get('name'));
},
alertName : function() {
    alert(this.model.get('name'));
}
});
var UsersView = Backbone.View.extend({
tagName : "ul",
id : "users-list",
subViews : [],
initialize : function(e) {
    $("body").html(this.el);
    this.collection = new Collection([{
        id : '4',
        name : 'candy'
    }, {
        id : '2',
        name : 'soap'
    }, {
        id : '3',
        name : 'pepper'
    }]);
    console.log(this.collection)

    this.render();
},
render : function() {
    var self = this;
    this.collection.forEach(function(model) {

        var cView = new UserView({
            model : model
        })
        self.subViews.push(cView);
        self.$el.append(cView.el);
    })

    this.$el.after("<a href='#home'>Go to home</a>");
},
close : function() {

    while (this.subViews.length) {
        this.subViews.pop().remove();

    }

    this.remove();
}
});
var Router = Backbone.Router.extend({
routes : {
    "" : "home",
    "home" : "home",
    "users" : "users"
},
initialize : function(options) {
    console.log('router')

 },

  home : function(e) {
     console.log('home')
     this.loadView(new HomeView());

 },
users : function(e) {
    console.log('users');
      this.loadView(new UsersView());

},
loadView : function(view) {
    this.view && (this.view.close ? this.view.close() : this.view.remove());
    this.view = view;
}
});
$(document).ready(function() {

var router = new Router();
Backbone.history.start({

});
});

1 个答案:

答案 0 :(得分:1)

过去这就是我所做的:

基本上,您要做的是在创建这些新ItemView时跟踪它们。在ItemsView上创建一个children哈希值model.cid或其他内容(用于快速查找)或只是一组视图。

remove上放置一个ItemsView函数,当被调用时,将调用超级Backbone.View#remove并遍历children并在每个函数上调用remove。< / p>

您还可以在removeItemView上放置一个Itemsview方法来获取模型并在children中查找,然后在其上调用remove