执行 Backbone where 和 findWhere 按值或引用返回模型

Do Backbone where and findWhere return model by value or reference

本文关键字:引用 返回 模型 Backbone where findWhere 执行      更新时间:2023-09-26

where(( 和 findWhere(( 方法是否在集合或模型副本中返回模型本身?正如我阅读的文档一样,它没有明确和具体地指出这种情况。

第一种方法,可以修改返回的结果,并在其上使用set()来添加新属性或直接更改现有属性的值,而无需在集合中包含此模型set()后调用add()

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

where(( 和 findWhere(( 函数的操作方式与各自的下划线.js命令类似。

这两种方法都返回对原始对象的引用。 find返回一个数组,而findWhere返回单个对象(或undefined(