个性化阅读
专注于IT技术分析

backbone.js集合排序sort

本文概述

在Backbone.js中,排序收集方法用于对集合中的项目进行排序。它与比较器属性一起使用,以便对项目进行排序。

句法:

collection.sort(options)

参数说明

options:它指定两个参数“ true”或“ false”以启用或禁用排序。

让我们以一个示例来部署排序收集方法。

请参阅以下示例:

<!DOCTYPE html>
   <head>
      <title>Sort 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 names will be displayed in ascending order.
         var Players = [
            {player: 'Ronaldo', id: '12'}, {player: 'Pele', id: '32'}, {player: 'Neymar', id:'18'}
          ];

          //'myteam' is a collection instance and model 'Player' is specified using model property
          var myteam = new Backbone.Collection(Players, {
             model:Player, //The comparator method is used to maintain the collection in sorted order
             comparator: 'player'
          });

          //display the sorted records, records are sorted based on player as we have set comparator to 'player'
          document.write("The sorted items are: ", JSON.stringify(myteam.toJSON()));
      </script>
   </body>
</html>

输出:

将以上代码保存在sort.html文件中,然后在新的浏览器中打开该文件。

赞(0)
未经允许不得转载:srcmini » backbone.js集合排序sort

评论 抢沙发

评论前必须登录!