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