where()和findWhere()方法是否在模型的集合或副本中返回模型本身? 正如我已经阅读了documentation,它没有明确地具体说明这一情况。
首先,可以修改返回的结果并在其上使用set()
来添加新属性或更改现有属性'在集合add()
之后直接调用set()
的值包括此模型。
答案 0 :(得分:1)
Backbone.js(以及一般的javascript)通过引用完成所有操作,因此除非明确这样做,否则永远不会克隆模型。您可以通过调用模型/集合上的.clone()
或将Backbone.Model传递给另一个模型构造函数(new Backbone.Model(model)
)来克隆模型。
在Backbone中,你可以在集合,数组,对象,任何东西之间移动模型,并且它们不会被克隆。
http://jsfiddle.net/CoryDanielson/Lj3r85ew/
var origModel = new Backbone.Model({ id: 0 });
// where and findWhere return the model instance, not clones.
var collection = new Backbone.Collection([origModel]),
where = collection.where({ id:0 })[0],
findWhere = collection.findWhere({ id:0 });
where === origModel; // true
findWhere === origModel; // true
-
// Cloning a model
var copy1 = origModel.clone(),
copy2 = new Backbone.Model(origModel.toJSON()),
copy3 = new Backbone.Model(origModel);
copy1 === origModel; // false
copy2 === origModel; // false
copy3 === origModel; // false
答案 1 :(得分:0)
where()和findWhere()函数的操作方式与各自的underscore.js命令类似。
两种方法都返回对原始对象的引用。 find
返回一个数组,而findWhere
返回一个对象(或undefined
)