BackboneJS - Collection Parse
描述
通过响应对象返回集合的数据,并以 JSON 格式表示数据。
语法
collection.parse(response, options)
参数
response − 它将模型属性数组返回到集合。
options − 它包含 true 作为选项,以 JSON 格式表示数据。
示例
<!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">
//'MyModel' 是模型名称,使用 Backbone.Model 类进行扩展
var MyModel = Backbone.Model.extend();
// 变量 'myData' 包含集合中需要解析的值
var myData = {
"values": [{
"fname": "Sachin",
"lname": "Tendulkar",
"country": "India"
}]
};
//'MyCollection' 是集合名称
var MyCollection = Backbone.Collection.extend ({
model: MyModel, //通过覆盖 'model' 属性指定模型 'MyModel'
parse : function(response, options) {
document.write(JSON.stringify(response));
}
});
//仅当 parse 设置为 true 时,集合实例 'myCollection' 才会提取 'myData' 的值
var mycollection = new MyCollection(myData, { parse: true });
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 parse.html 文件中。
在浏览器中打开此 HTML 文件。

backbonejs_collection.html