我使用纯 JS 指令进行渲染:
http://beebole.com/pure/documentation/rendering-with-directives/
如果模板中的节点缺失,Pure JS 的默认行为是崩溃,原因是:
The node "XXX" was not found in the template
这种默认行为是完全可以理解的,因为它确保模板中没有不一致之处。但是,在相同的情况下,人们希望跳过失败的分配并继续进行其余的分配(可能记录错误),以避免由于单个错误/拼写错误导致整个渲染失败。
有什么方法可以用 Pure JS 获得这种行为吗?我可以告诉 Pure JS 只渲染一个元素“如果它存在”吗?
最佳答案
不幸的是当前稳定版本Pure JS (修订版:2.79)不允许呈现元素“如果它存在”?
以下纯代码片段显示了错误是如何抛出的:
if(selector === '.' || ( !selector && attr ) ){
target[0] = dom;
}else{
target = plugins.find(dom, selector);
}
if(!target || target.length === 0){
return error('The node "' + sel + '" was not found in the template:\n' + outerHTML(dom).replace(/\t/g,' '));
}
如您所见,如果未找到 target
(通过 jQuery、dojo 等库之一),则会抛出上述错误。
我在这种情况下使用的解决方法如下:
- 我将模板与所有可能的元素一起使用,这样 Pure 就不会抛出错误
- 使用 CSS 类隐藏了一些元素(例如显示错误消息等)
- 我使用 Pure 和 JavaScript 函数更改 CSS 类,并根据输入数据根据指令隐藏/显示元素。
关于javascript - Pure JS 可以使用 "Conditional Rendering"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945116/