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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。