简体   繁体   English

Backbone.js - 替换集合中的现有模型

[英]Backbone.js - Replace existing model in collection

I have the following collection: 我有以下集合:

UsersMod.users_list = Backbone.Collection.extend({

    add : function(model) {

        var duplicate = this.any(function(_model) { 

            return _model.get('user') === model.get('user');

        });

        if (duplicate) {

            return false;

        }

        Backbone.Collection.prototype.add.call(this, model);

    }

});

This currently checks for a duplicate model in the collection and returns false if one is found. 这当前检查集合中的重复模型,如果找到,则返回false。 What I'm trying to do is when a duplicate is found, remove the old one and replace it with the new one. 我要做的是当找到副本时,删除旧副本并将其替换为新副本。

Any help is much appreciated, thanks in advance :) 非常感谢任何帮助,在此先感谢:)

Try this: 尝试这个:

UsersMod.users_list = Backbone.Collection.extend({

    add : function(model) {

        var duplicates = this.filter(function(_model) { 

            return _model.get('user') === model.get('user');

        });

        if (! _(duplicates).isEmpty) {

            this.remove(duplicates);

        } 

        Backbone.Collection.prototype.add.call(this, model);

    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM