gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:12:02 25 4
gpt4 key购买 nike

where() 和 findWhere() 方法返回集合中的模型本身还是模型的副本?正如我读过的documentation它没有明确具体地说明这种情况。

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

最佳答案

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

关于javascript - 执行 Backbone where 和 findWhere 按值或引用返回模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27534811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com