【问题标题】:Why can I call function which is in a shadow dom?为什么我可以调用 shadow dom 中的函数?
【发布时间】:2014-12-04 11:02:31
【问题描述】:

我创建了一个名为“memory-box”的自定义元素,如下面的代码。
请注意“memory-box-template”中的“logthis”函数。

memory-box.html

<template id="memory-box-template">
    <input id="memory-box" type="form" />
    <input type="button" id="testbutton" />
    <script type="text/javascript">
    function logthis(me){
        console.log(me);
    }    
    </script>
</template>

<script type="text/javascript">
    (function() {
        var thisDoc = document.currentScript.ownerDocument;
        var storage = localStorage;

        var proto = Object.create(HTMLElement.prototype, {
            createdCallback: {
                value: function() {                
                    var temp = thisDoc.querySelector('#memory-box-template');
                    var con = document.importNode(temp.content, true);
                    this.createShadowRoot().appendChild(con);
                    var input = this.querySelector('::shadow #memory-box');
                    var data = storage.getItem(this.id);
                    input.value = data;
                    input.addEventListener('input', saveData.bind(input, this.id));
                }
            },
        });

        document.registerElement('memory-box', {
            prototype: proto
        });

        function saveData(id, e) {
            storage.setItem(id, this.value);
        }
    })();
</script>

现在,我像下面的代码一样使用自定义元素“memory-box”。

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <link rel="import" href="/html/memory-box.html">
</head>

<body>
    <div><memory-box id="memory1"></memory-box></div>
    <div><memory-box id="memory2"></memory-box></div>
    <div><memory-box id="memory3"></memory-box></div>
    <div><memory-box id="memory4"></memory-box></div>   
</body>

<script type="text/javascript">
    logthis(this);
</script>

</html>

如你所见,我在 index.html 中放了一个脚本,并调用函数“logthis”只是因为我很好奇。并且没有发生错误。
为什么?
函数“logthis”在每个影子域中。应该是不能在shadow dom之外调用吧。

【问题讨论】:

    标签: javascript web-component shadow-dom custom-element


    【解决方案1】:

    正如 here 所解释的,虽然 Shadow DOM 中的 HTML 是封装的,但任何 JavaScript 都不是——它在全局范围内,除非您使用特定的 javascript 技术(命名空间、IIFE)来这样做。

    希望这会有所帮助,

    乔纳森·多德

    【讨论】:

    • 我希望这将允许使用组件的本地范围绑定内联事件处理程序onclick0"fooBar()"... 可惜。它会使编写声明式 Javascript 而不是命令式的变得容易得多。我试图弄清楚如何避免影响全局范围,但除了命名空间之外我没有找到任何建议。
    • 请更新链接到explanation
    猜你喜欢
    • 2017-07-02
    • 1970-01-01
    • 2013-05-16
    • 2019-06-29
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多