[英]Why are custom events preferred over attribute callbacks in web-components?
[英]custom web component callbacks
我很難解釋這一點。 我正在構建一個自定義組件,在這個組件中有一個按鈕。 我需要能夠動態設置該按鈕的單擊操作,以便其操作可以根據上下文進行更改。 因此,如果此組件有 2 個實例 a&b,則每個實例都有一個不同的 function,當單擊其中的按鈕時,該實例將執行。 我想我可以將 function 分配給組件的屬性並從組件內部執行該屬性,如下所示:
window.customElements.define('xmp-1', class xmp1 extends HTMLElement{ constructor(){super();} connectedCallback(){ this.innerHTML = ` <div> <div id='test' style='width:70px; border:solid thin black;'>test button</div> </div>`; this.querySelector('#test').addEventListener('click', function(){ console.log('test action'); this.action1(); }); } }); document.querySelector('xmp-1').action1 = function(){ console.log("this is the callback"); };
<xmp-1></xmp-1>
但是當你運行它時,你會得到一個錯誤,說屬性action1
不存在。
設置允許我需要的靈活性的回調的正確方法是什么?
更新:請嘗試下面的代碼,我在其中添加了一個綁定語句來綁定“this”
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
document.querySelector('xmp-1').action1 = function(){
console.log("this is the callback");
};
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super();
this.handler = this.handler.bind(this);
}
handler() {
console.log("this is the test");
console.log('test action');
this.action1();
}
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click',this.handler);
}
});
</script>
</body>
</html>
請在您的代碼中將 xmp-1更改為#test ,如下所示,
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.addEventListener('load', (event) => {
document.querySelector('#test').action1 = function(){
console.log("this is the callback");
};
});
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
}
});
</script>
</body>
</html>
或者請嘗試如下所示的方法 2,您必須在其中添加一個名為this.querySelector('#test').action1的 function 到您的自定義元素。
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<xmp-1></xmp-1>
<script>
window.customElements.define('xmp-1', class xmp1 extends HTMLElement {
constructor() { super(); }
connectedCallback() {
this.innerHTML = `<div>
<div id='test' style='width:70px; border:solid thin black;'>test button</div>
</div>`;
this.querySelector('#test').addEventListener('click', function () {
console.log('test action');
this.action1();
});
this.querySelector('#test').action1 = function() {
console.log('test action1');
}
}
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.