BackboneJS - Collection Sort
描述
集合排序命令对集合中的项目进行排序,并使用 comparator 属性对项目进行排序。
语法
collection.sort(options)
参数
options − 它包含可选参数,例如 true 或 false,用于禁用或启用排序。
示例
<!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">
var Player = Backbone.Model.extend(); //'Player' is a model name
//变量 'Players' 包含要按升序显示的项目
var Players = [
{player: 'sachin',id: '44'},
{player: 'ganguly',id: '22'},
{player: 'dhoni',id:'33'}
];
//'myteam' 是一个集合实例,使用模型属性指定模型 'Player'
var myteam = new Backbone.Collection (Players, {
model:Player,
//比较器方法用于维护按排序顺序排列的集合
comparator: 'player'
});
//显示已排序的记录,记录基于Player排序,因为我们已将比较器设置为 'player'
document.write("已排序的项目是: ",JSON.stringify(myteam.toJSON()));
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
Save the above code in the sort.htm file
在浏览器中打开此 HTML 文件。

backbonejs_collection.html