更新:
您可以使用 DataItem API 通过原型来管理您的数据。
您不能将 JSON 对象直接绑定到模板,您必须将它们转换为 DataItem 对象。检索所需的部分元素并为该部分创建一个新数据项。从 JSON 对象创建新数据项。setPropertyPath 方法用于将新数据项绑定到节数据项。清单 5-4 显示了一个修改后的 parseJson 函数,它从 Images.json 文件中获取信息,将它们转换为数据项,并将它们绑定到适当的部分。
使用原型元素,您可以创建包含类似对象的单个锁定。在锁定内部,您定义锁定的结构。清单 5-5 显示了一个锁定,它显示了在 type 元素中定义为艺术品的对象。每个图像的 URL 和标题都是从 JSON 对象中提取的。
<prototypes>
<lockup prototype="artwork">
<img binding="@src:{url};" width="200" height="300"/>
<title binding="textContent:{title};" />
</lockup>
</prototypes>
<section binding="items:{images};" />
以下使用items
from迭代并填充您的原型代码section
:
function parseJson(information) {
var results = JSON.parse(information);
let parsedTemplate = templateDocument()
navigationDocument.pushDocument(parsedTemplate)
let shelf = parsedTemplate.getElementsByTagName("shelf").item(0)
let section = shelf.getElementsByTagName("section").item(0)
//create an empty data item for the section
section.dataItem = new DataItem()
//create data items from objects
let newItems = results.map((result) => {
let objectItem = new DataItem(result.type, result.ID);
objectItem.url = result.url;
objectItem.title = result.title;
return objectItem;
});
//add the data items to the section's data item; 'images' relates to the binding name in the protoype where items:{images} is all of the newItems being added to the sections' data item;
section.dataItem.setPropertyPath("images", newItems)
}
模板:
<document>
<stackTemplate>
<banner>
<title>JSON Shelf</title>
</banner>
<collectionList>
<shelf>
<prototypes>
<lockup prototype="artwork">
<img binding="@src:{url};" width="200" height="300"/>
<title binding="textContent:{title};" />
</lockup>
</prototypes>
<section binding="items:{images};" />
</shelf>
</collectionList>
</stackTemplate>
</document>
参考:
https://developer.apple.com/library/content/documentation/TVMLKitJS/Conceptual/TVMLProgrammingGuide/GeneratingContentForYourApp.html
希望它可以帮助你。