【问题标题】:Do i have to delete unused views on backbone.js我是否必须删除backbone.js 上未使用的视图
【发布时间】:2014-01-22 11:28:03
【问题描述】:
var Home = Backbone.View.extend({
template: _.template($('#home-template').html()),

initialize: function (params) {
    this.collection = new BlogList();

    this.listenTo(this.collection, "add", this.renderBlog);
    this.listenTo(this.collection, "reset", this.render);
},

render: function () {
    this.$el.html(this.template({hasPrevious: this.collection.hasPrevious()}));

    this.collection.each(function(item) {
        this.renderBlog(item);
    }, this);

    return this;
},

renderBlog: function(item) {
    this.$('#blog-list-container').append((new BlogPreView({ model: item })).render().el);
},

BlogPreView 是一个 Backbone.View 一个新的 BlogPreView 被多次实例化。我需要删除旧的吗?

如何删除一个backbone.view 以及在这个具体示例中如何删除?

【问题讨论】:

    标签: javascript backbone.js memory-leaks backbone-views


    【解决方案1】:

    您应该在您的视图上调用remove 以删除它们。这将从 DOM 中删除 el 并调用 stopListening 以撤消您所做的任何 listenTo 调用。如果还有其他东西要清理,那么你应该重写remove来清理这些“其他东西”,然后调用标准的remove

    在您的情况下,您有子视图,因此您应该跟踪它们:

    renderBlog: function(item) {
        var v = new BlogPreView({ model: item });
        this.previews.push(v); // Initialize this in `initialize` of course.
        this.$('#blog-list-container').append(v.render().el);
    }
    

    然后在重新渲染或删除之前清理它们:

    removePreviews: function() {
        _(this.previews).invoke('remove');
        this.previews = [ ];
    },
    render: function() {
        this.removePreviews();
        // what you have now goes here...
    },
    remove: function() {
        this.removePreviews();
        return Backbone.View.prototype.remove.apply(this);
    }
    

    您通常无需致电 remove 就可以逃脱,但是一旦您发现确实需要它,将您的代码正确地改造成 remove 事情可能会很麻烦。但是,如果您一直调用remove,正确跟踪子视图,并根据需要覆盖remove,那么您以后就不会因为进行不愉快的改造而陷入困境。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2015-01-03
      相关资源
      最近更新 更多