backbone.js集合add

本文概述

  • 参数说明
Backbone.js Collection Add方法用于将模型或模型数组添加到集合中。
句法:
collection.add(models, options)

参数说明模型:它包含集合实例的名称,需要在集合中添加它们。
选项:包括模型类型,并将它们添加到集合实例中。
让我们举个例子。
请参阅以下示例:
< !DOCTYPE html> < head> < title>Add Collection Example< /title> < script src="http://img.readke.com/220416/043P44G2-0.jpg" type="text/javascript">< /script> < script src="http://img.readke.com/220416/043P43334-1.jpg" type="text/javascript">< /script> < script src="http://img.readke.com/220416/043P45G3-2.jpg" type="text/javascript">< /script> < /head> < body> < script type="text/javascript"> //Consider a model 'Player' containing default values. var Player = Backbone.Model.extend({ defaults: { name: "Sachin", country:"India" } }); //The 'PlayersCollection' is a collection instance and model 'Player' is specified by overriding the 'model' property var PlayersCollection = Backbone.Collection.extend({ model: Player }); //The instances "player1" and "player2" are created for the model "Player" var player1 = new Player({name: "Dhoni", country:"India"}); var player2 = new Player({name: "Sehwag", country:"India"}); var player3 = new Player({name: "Virat", country:"India"}); //The add() method adds the models 'player1''player2' and'player3' to the collection instance 'mycollection' var mycollection = new PlayersCollection(); mycollection.add([player1, player2, player3]); //The 'length' property deteremines length of the collection document.write('Number of added players : ' + mycollection.length); < /script> < /body> < /html>

输出:
【backbone.js集合add】将上面的代码保存在add.html文件中,并在新的浏览器中打开该文件:
backbone.js集合add

文章图片

    推荐阅读