在Backbone.js中,比较器属性用于按排序顺序维护集合。默认情况下,没有用于集合的比较器。
句法:
collection.comparator
让我们举个例子。
请参阅以下示例:
<
!DOCTYPE html>
<
head>
<
title>Comparator Collection Example<
/title>
<
script src="http://img.readke.com/220416/052IB5H-0.jpg" type="text/javascript"><
/script>
<
script src="http://img.readke.com/220416/052I643b-1.jpg" type="text/javascript"><
/script>
<
script src="http://img.readke.com/220416/052I61242-2.jpg" type="text/javascript"><
/script>
<
/head>
<
body>
<
script type="text/javascript">
var MyModel = Backbone.Model.extend();
//'LangNames' is a model name//'mydata' variable contains values to be displayed in sorted order
var mydata = http://www.srcmini.com/[
{id:4, name:'Sachin Tendulkar'}, {id:2, name: 'Rahul Dravid'}, {id:3, name: 'Saurav Ganguly'}
];
//'myval' is a collection instance and includes array of values stored in 'mydata' variable
var myval = new Backbone.Collection(mydata, {
model:MyModel, //The model 'MyModel' is specified by overriding the "model" property
comparator: 'name'//The 'comparator' maintain the collection in sorted order
});
//Here, displaying the array of values using collection instance 'myval' and 'models' method
document.write("The sorted (based on name) order of collection: ", JSON.stringify(myval)
);
<
/script>
<
/body>
<
/html>
输出:
【backbone.js集合比较器comparator】将以上代码保存在compare.html文件中,并在新的浏览器中打开该文件。
文章图片
推荐阅读
- backbone.js集合排序sort
- backbone.js集合length
- backbone.js集合slice
- backbone.js集合shift
- backbone.js集合unshift
- backbone.js集合at
- backbone.js集合pop
- backbone.js集合push
- backbone.js集合get