1
我创建了一个名为“memory-box”的自定义元素,就像下面的代码一样。
请注意“存储箱模板”中的“logthis”功能。为什么我可以调用阴影中的函数?
内存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>
现在,我使用自定义元素 “记忆盒” 像下面的代码。
的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”在每个影子doms中。我认为它应该不能在影子之外被调用。
我希望这将允许使用的可能性onclick0“Foobar的()”的''成分的局部范围,结合内嵌的事件处理程序...这是一个遗憾。这会让编写声明式JavaScript变得容易得多,而不是迫切需要。我试图找出如何避免触发全局范围,但除了名称空间之外,我还没有找到任何建议。 – 2017-10-16 15:57:13