- BackboneJS 教程
- BackboneJS - 首頁
- BackboneJS - 概述
- BackboneJS - 環境設定
- BackboneJS - 應用程式
- BackboneJS - 事件
- BackboneJS - 模型
- BackboneJS - 集合 (Collection)
- BackboneJS - 路由器
- BackboneJS - 歷史
- BackboneJS - 同步
- BackboneJS - 檢視
- BackboneJS - 實用工具
- BackboneJS 有用資源
- BackboneJS - 快速指南
- BackboneJS - 資源
- BackboneJS - 討論
BackboneJS - 集合 At
描述
它用於透過指定索引從集合中檢索模型。
語法
collection.at(index)
引數
index - 這是索引位置,我們可以在其中從集合中獲取模型。
示例
<!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">
//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: "dhoni" });
var player2 = new Player({id:2, name: "raina"});
//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: "yuvraj" });
//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.htm檔案中。
在瀏覽器中開啟此 HTML 檔案。
backbonejs_collection.htm
廣告