是“条件渲染”吗?可以用纯JS吗?

发布于 2024-12-28 06:20:56 字数 446 浏览 2 评论 0原文

我使用纯 JS 指令进行渲染:

http://beebole.com/pure/documentation /rendering-with-directives/

如果模板中的节点丢失,纯 JS 的默认行为是崩溃,因为:

模板中未找到节点“XXX”

此默认行为是完全可以理解的,因为它确保模板中不存在不一致。但在相同的情况下,人们希望跳过失败的分配并继续其余的分配(可能记录错误),以避免整个渲染因单个错误/拼写错误而失败。

有什么方法可以用纯 JS 获得这种行为吗?我可以告诉 Pure JS 仅渲染一个元素“如果它存在”吗?

I use Pure JS directives for rendering:

http://beebole.com/pure/documentation/rendering-with-directives/

If a node in the template is missing, the default behaviour of Pure JS is to crash due to:

The node "XXX" was not found in the template

This default behaviour is totally comprehensible, because it ensures there are no inconsistencies in the template. In same cases, though, one would like to skip a failing assignment and to proceed with the rest of the assignments (possibly logging the error), to avoid the whole rendering to fail because of a single error / typo.

Is there any way to obtain this behaviour with Pure JS? Can I tell Pure JS to render an element just "if it exists"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

来世叙缘 2025-01-04 06:20:56

不幸的是,当前稳定版本的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 类根据输入数据隐藏/显示元素的指令。

Unfortunately current stable version of Pure JS (revision: 2.79) does not allow to render an element "if it exists"?

The following Pure code snippet shows how the error is thrown:

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,'  '));
}

As you can see, if target has not been found (by one of libraries such as jQuery, dojo etc.) then the mentioned error is thrown.


Workaround I use in that kind of situations is as follows:

  • I use template with all possible elements so that Pure does not throw errors
  • Some elements (e.g. displaying error messages etc.) are hidden using CSS classes
  • I change CSS classes using Pure and JavaScript functions with directives to hide / show elements depending on input data.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文