Backbone.js 集合集方法使用模型中的一組項目執行集合的智能更新。如果列表中的模型尚未在集合中,它將被添加;如果模型已經在集合中,它的屬性將被合並。
用法:
collection.set(models,options)
參數說明:
models:它指定集合的實例以及要在集合中設置的值。
options:它包含 id、name 等參數來設置集合中的值。
讓我們舉個例子。
看這個例子:
<!DOCTYPE html>
<head>
<title>Set 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
});
var player1 = new Player({ name:"Dravid" }); //'player1' is instance of the model
var mycollection = new PlayersCollection(); //'mycollection' is instance of the collection
mycollection.add(player1); //adding model instance 'player1' along with value to the collection
//The set() method update the 'player1' model by passing this value in the collection
mycollection.set([player1, { name:"Ganguly" }]);
document.write(JSON.stringify(mycollection.toJSON()));
</script>
</body>
</html>
輸出:
將上述代碼保存在 set.html 文件中,然後在新瀏覽器中打開該文件。

相關用法
- Backbone.js collection.slice()用法及代碼示例
- Backbone.js collection.sort()用法及代碼示例
- Backbone.js collection.sync()用法及代碼示例
- Backbone.js collection.shift()用法及代碼示例
- Backbone.js collection.parse()用法及代碼示例
- Backbone.js collection.clone()用法及代碼示例
- Backbone.js collection.fetch()用法及代碼示例
- Backbone.js collection.url()用法及代碼示例
- Backbone.js collection.length()用法及代碼示例
- Backbone.js collection.push()用法及代碼示例
- Backbone.js collection.add()用法及代碼示例
- Backbone.js collection.where()用法及代碼示例
- Backbone.js collection.pop()用法及代碼示例
- Backbone.js collection.create()用法及代碼示例
- Backbone.js collection.comparator()用法及代碼示例
- Backbone.js collection.findWhere()用法及代碼示例
- Backbone.js collection.unshift()用法及代碼示例
- Backbone.js collection.reset()用法及代碼示例
- Backbone.js collection.get()用法及代碼示例
- Backbone.js collection.pluck()用法及代碼示例
注:本文由純淨天空篩選整理自 Backbone.js collection.set()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。