1
아래 코드와 같이 "memory-box"라는 맞춤 요소를 만들었습니다.
"memory-box-template"에있는 "logthis"함수에주의하십시오.왜 그림자 DOM에있는 함수를 호출 할 수 있습니까?
메모리 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에 있습니다. 그림자 돔 밖에서는 호출 할 수 없다고 생각합니다.
조나단 도드 나는이 가능성 "는 foobar()"'onclick0 구성 요소 '의 로컬 범위를 사용하여 인라인 이벤트 처리기를 바인딩 할 수있는 것입니다 희망 ... 그것은 유감이다 . 선언적 자바 스크립트를 쓰는 것이 훨씬 쉬워졌습니다. 전역 범위를 피하는 방법을 알아 내려고 노력하고 있지만 네임 스페이스를 제외한 모든 조언을 찾지 못했습니다. –