BackboneJS - Collection Initialize
描述
创建模型实例时,通过在创建集合时定义 initialize 函数来调用它。
语法
new Backbone.Collection(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">
//模型 'MyTeam' 包含默认值,并使用
//Backbone.Model 类进行扩展
var MyTeam = Backbone.Model.extend ({
defaults: {
player: "sachin",
country: "india"
},
//通过定义初始化函数调用模型实例
initialize: function() {
document.write("Welcome to TutorialsPoint!!!");
}
});
//'MyTeam1' 是一个集合实例,模型 'MyTeam' 通过
//覆盖 'model' 属性指定
var MyTeam1 = Backbone.Collection.extend ({
model: MyTeam
});
var player1 = new MyTeam ({
player: "sehwag",
country: "india"
});
//'player1' 是一种集合类型,通过在集合中传递模型对象
var myval = new MyTeam1([player1]);
//'myval.models' 定义集合内的模型数组
document.write("<br>"+JSON.stringify(myval.models));
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 initialize.html 文件中。
在浏览器中打开此 HTML 文件。