当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Backbone.js collection.at()用法及代码示例


Backbone.js 集合 at 方法用于使用指定索引从集合中检索模型。

用法:

index()

参数说明:

index:它为可以从集合中检索模型的索引位置提供种类。

让我们举个例子。

看这个例子:

<!DOCTYPE html>
   <head>
      <title>At 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">
         //The model name is 'Player' and contains default values
         var Player = Backbone.Model.extend({
            defaults:{
               id:"",
               name:""
            }
         });

         //'PlayersCollection' is an instance of the collection
         var PlayersCollection = Backbone.Collection.extend({
            model:Player  //model 'Player' is specified by using model property
         });
         var player1 = new Player({id:1, name:"Dravid" });
         var player2 = new Player({id:2, name:"Ganguly"});

           //The add() method adds the models 'player1' and 'player2' to the collection instance 'mycollection'
         var mycollection = new PlayersCollection();
         mycollection.add([player1,player2]);
         document.write('<b>Players added are:</b> ' + JSON.stringify(mycollection.toJSON()));
         var player3 = new Player({id:3, name:"Sehwag" });

         //Here, adding the model 'player3' at 0th index of the collection
         mycollection.add(player3,{at:0});

         //display all the models added. player3 will be added at the 0th position
         document.write('<br><b>Now the new list of players is:</b> ' + JSON.stringify(mycollection.toJSON()));
      </script>
   </body>
</html>

输出:

将上述代码保存在 at.html 文件中,然后在新浏览器中打开此文件。

BackboneJS at Collection



相关用法


注:本文由纯净天空筛选整理自 Backbone.js collection.at()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。