- BackboneJS 教程
- BackboneJS - 主頁
- BackboneJS - 概覽
- BackboneJS - 環境設定
- BackboneJS - 應用程式
- BackboneJS - 事件
- BackboneJS - 模型
- BackboneJS - 集合
- BackboneJS - 路由
- BackboneJS - 歷史
- BackboneJS - 同步
- BackboneJS - 檢視
- BackboneJS - 實用程式
- BackboneJS 有用資源
- BackboneJS - 快速指南
- BackboneJS - 資源
- BackboneJS - 討論
BackboneJS - 集合設定
描述
用於使用模型中的專案集更新集合。如果找到任何新模型,這些專案將被新增到該模型。
語法
collection.set(models,options)
Parameters
models - 它包含集合的例項以及要設定的集合值。
options - 它包含 ID、名稱等引數來設定集合中的值。
<!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">
//Here the model name is 'Player' and contains default value
var Player = Backbone.Model.extend ({
defaults: {
name: 'sachin'
},
});
//'PlayersCollection' is an instance of collection
var PlayersCollection = Backbone.Collection.extend ({
model: Player //model 'Player' is specified by using model property
});
//'player1' is instance of the model
var player1 = new Player({ name: "dhoni" });
//'mycollection' is instance of the collection
var mycollection = new PlayersCollection();
//adding model instance 'player1' along with value to the collection
mycollection.add(player1);
//The set() method update the 'player1' model by passing this value in the collection
mycollection.set([player1, { name: "raina" }]);
document.write(JSON.stringify(mycollection.toJSON()));
</script>
</body>
</html>
輸出
讓我們執行以下步驟,看看上面的程式碼是如何工作的 -
將以上程式碼儲存在 set.htm 檔案中。
在瀏覽器中開啟此 HTML 檔案。
backbonejs_collection.htm
廣告