BackboneJS - Collection Set
描述
它用于使用模型中的一组项目更新集合。如果发现任何新模型,则项目将添加到该模型中。
语法
collection.set(models,options)
参数
models − 它包括集合的实例以及要在集合中设置的值。
options − 它包括 id、name 等参数,用于设置集合中的值。
<!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"> //此处模型名称为"Player",包含默认值 var Player = Backbone.Model.extend ({ defaults: { name: 'sachin' }, }); //"PlayersCollection"是集合的一个实例 var PlayersCollection = Backbone.Collection.extend ({ model: Player //模型"Player"由模型属性指定 }); //"player1"是模型的实例 var player1 = new Player({ name: "dhoni" }); //"mycollection"是集合的实例 var mycollection = new PlayersCollection(); //将模型实例"player1"连同值一起添加到集合中 mycollection.add(player1); //set() 方法通过在集合中传递此值来更新"player1"模型 mycollection.set([player1, { name: "raina" }]); document.write(JSON.stringify(mycollection.toJSON())); </script> </body> </html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 set.html 文件中。
在浏览器中打开此 HTML 文件。