BackboneJS - Collection findWhere
描述
它类似于 where 方法,但直接返回集合中与传递的属性匹配的第一个模型。
语法
collection.findWhere(attributes)
参数
attributes − 它们表示已定义模型的属性。
示例
<!DOCTYPE html>
<html>
<head>
<title>Collection Example</title>
<script src = "https://code.jquery.com/jquery-2.1.3.min.js"
type = "text/javascript"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
type = "text/javascript"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
type = "text/javascript"></script>
</head>
<body>
<script type = "text/javascript">
//'Players' 是模型名称并包含默认值
var Players = Backbone.Model.extend ({
defaults: {
id:"",
name: "",
country:""
}
});
//'PlayersCollection' 是该集合的一个实例
var PlayersCollection = Backbone.Collection.extend ({
//模型"Players"是通过覆盖集合的"model"属性来指定的
model: Players
});
$(function() {
var mycollection = new PlayersCollection();
// set() 方法设置 'id'、'name' 和 'country' 的值
// 在模型"Players"中指定的属性
mycollection.set ([
{id:1, name: 'dhoni', country:'india'},
{id:2, name:'gayle', country:'west indies'},
{id:3, name: 'maxwell', country:'australia'},
{id:4, name: 'duminy', country:'south africa'}
]);
// findWhere() 方法查找包含 id 为"1"的模型
var res = mycollection.findWhere({id:1});
//以 JSON 格式显示结果
document.write("匹配属性的值为: ",JSON.stringify(res));
});
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 findwhere.html 文件中。
在浏览器中打开此 HTML 文件。

backbonejs_collection.html