骨干.js - 从推文中删除模型时出现奇怪的问题

Backbone.js - weird issue when removing a model from a tweet.

本文关键字:问题 模型 js 删除 文中 骨干      更新时间:2023-09-26

我在骨干网方面遇到了一些问题.js。 虽然我的所有代码都可以工作,但我确实得到了一个异常: TypeError: 'undefined' is not an object (evaluating '(e=this.models[c]).cid') .

当模型数量超过限制时,就会发生异常,我在集合中调用 self.remove()。

var Column = Backbone.Collection.extend({
    initialize: function(col) {
        var view = new ColumnView({
            id: "column_" + col.id,
            column: col
        });
        view.render();
    },
    comparator: function(tweet) {
        return tweet.get('created_at_time');
    },
    clean: function() {
        var self        = this;
        var total       = this.models.length;
        var threshold   = (total - window.config.threshold) - 1;
        if(threshold > 0) {
            console.log("Removing if tweet is older then " + threshold);
            this.models.forEach(function(tweet, index) {
                if(index < threshold) {
                    self.remove(tweet);
                }
            });
        }
    }
});

有谁知道发生了什么?该错误发生在野生动物园上。

猜测一下,这是由于您在迭代模型列表时删除模型而导致的。

尝试

if (threshold > 0) {
    var removed = [];
    this.models.forEach(function (tweet, index) {
        if (index < threshold) {
            removed.push(tweet);
        }
    });
    this.remove(removed);
}

或@mu建议的变体

if (threshold > 0) {
    var removed =  this.filter(function(model, index) {
            return index < threshold;
    });
    this.remove(removed);
}

或者在您的情况下可能更简单

if (threshold > 0) {
    this.remove(this.models.slice(0, threshold));
}