123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 | //set/add操作中传入set 的默认option var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; set:function(models, options){ //各种属性设置 options = _.defaults({}, options, setOptions); //parse 解析models if (options.parse) models = this.parse(models, options); //判断是否是当个model,如果是则返回一个[model] var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); // 各种options 的判断 var i, l, id, model, attrs, existing, sort; // 如果传入了at属性,则会在插入的时候插入到at指定的models的位置 var at = options.at; var targetModel = this.model; //如果comparator不为空,没有指定at,sort不为false,则这次set操作将进行排序 var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; //设置各个操作的临时存储集合 var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; //开始对传入的models进行处理,但是只是对models进行分类,传入到各个临时存储集合中去 for (i = 0, l = models.length; i < l; i++) { attrs = models[i] || {}; //获取model的id if (attrs instanceof Model) { //是否为 Backbone.Model (没有设置model) id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute || 'id']; } //判断是否已经存在 if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; //如果 remove 为true,加入modelMap if (merge) { //merge 为true, 对model中的attribute 进行设置 attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options);//调用model中的set方法,进行数据合并 if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; } else if (add) {//若不存在则判断add属性,存入到toAdd 中 //调用_prepareModel生成一个model model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); //添加入toAdd this._addReference(model, options); //建立与collection的关联 } model = existing || model; if (order && (model.isNew() || !modelMap[model.id])) order.push(model); modelMap[model.id] = true; } //添加model 处理 if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length;//更新length的值 if (at != null) {//如果at值不为空,则插入到对应的索引位置 for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else {//否则使用push向后插入,如果order不为空,则使用order替换整个models if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } if (sort) this.sort({silent: true}); // 排序 //触发 响应的事件 if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } return singular ? models[0] : models; } |