BackboneJS - Collection Push
描述
它类似于 add() 方法。它在集合的末尾添加一个模型。
语法
collection.push(models, options)
参数
models − 它包含集合实例的名称,这些实例被推送到集合中。
options − 它包括模型类型并将它们添加到集合实例中。
示例
<!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: { c_id:"", country: "" } }); //"PlayersCollection"是集合实例,模型"Player"通过使用指定 //model 属性 var PlayersCollection = Backbone.Collection.extend ({ model: Player }); //"country1"、"country2"和"country3"是模型"Player"的实例 var country1 = new Player({c_id:1, country: "australia" }); var country2 = new Player({c_id:2, country: "england"}); var country3 = new Player({c_id:3, country: "india"}); var mycollection = new PlayersCollection(); //此处,push() 方法将上述模型添加到集合中 mycollection.push(country1); mycollection.push(country2); mycollection.push(country3); //'length' 属性定义集合中的模型总数 document.write('添加的国家/地区数量:' + mycollection.length); </script> </body> </html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 push.html 文件中。
在浏览器中打开此 HTML 文件。