我一直致力于为 Apple TV 上的 tvOS 应用程序动态生成 tvml 模板,其中包含非常频繁更改的内容。生成模板工作正常,但是在视图之间来回导航或离开并重新进入应用程序时,我无法让应用程序更新/重新加载模板的内容。只有重新启动似乎会重新加载 tvml 模板。
4 回答
每当您在模板文档中操作 TVML 时,您的模板都会自动刷新。
如果您像这样维护对文档的引用:
var myDoc;
resourceLoader.loadResource(templateURL,
function(resource) {
if (resource) {
myDoc = self.makeDocument(resource);
});
}
您可以使用 myDoc 操作TVML,您的视图将自动更改。
因此,如果您的模板文档包含“collectionList”并且您要运行此代码:
//Removes the child elements of the first collectionList
var collectionLists = myDoc.getElementsByTagName("collectionList");
var collectionList = collectionLists.item(0);
while (collectionList.firstChild) {
collectionList.removeChild(collectionList.firstChild);
}
您的视图将不再显示 collectionList 中的 UI 元素。代码运行时,视图将自行刷新。
如果您使用的是atvjs框架,您可以轻松创建并导航到在导航时重新生成的动态页面。
ATV.Page.create({
name: 'home',
url: 'path/to/your/api/that/returns/json',
template: your_template_function
});
// navigate to your page
ATV.Navigation.navigate('home');
@shirefriendship 的回答为我指明了正确的方向(谢谢!)。再举一个例子,如果您想更改模板中单个元素的文本(例如描述),则需要使用以下innerHTML
属性:
function changeDescription(incomingString) {
console.log("inside the change description function")
if (incomingString) {
var theDescription = myDoc.getElementsByTagName("description").item(0);
theDescription.innerHTML = incomingString;
}
}
这会立即将描述更改给查看者。
在 API 的标头中进行设置:
缓存控制:无缓存
从 Apple Docs 获得:https ://developer.apple.com/library/tvos/documentation/General/Conceptual/AppleTV_PG/YourFirstAppleTVApp.html
重要的
从 Web 服务器提供 JavaScript 和 XML 文件时,您通常需要确保对页面的任何更改始终对客户端应用程序可见。为此,您的服务器必须确保客户端不缓存任何页面。当您的服务器响应对不应缓存页面的 HTTP 请求时,服务器应在 HTTP 响应标头中包含 Cache-Control:no-cache。