Adding component with parameters

This commit is contained in:
Julien Lengrand-Lambert
2017-11-23 12:05:47 +01:00
parent 4ac8d920d6
commit 6211fa3797
2 changed files with 38 additions and 2 deletions

View File

@@ -8,10 +8,18 @@
<p>In this workshop, we will create new custom HTML Components</p>
<hello-world></hello-world>
<button onclick="removeHelloWorld()">Click me</button>
<hello-world-with-params name="Meetup"></hello-world-with-params>
<div>
<button onclick="removeHelloWorld()">Click me to remove Hello World</button>
</div>
<div>
<input type="text" id="hello-world-param">
<button onclick="changeHelloWorldParam()">Click me to change Hello World's parameter</button>
</div>
<script src="src/components/hello-world.js"></script>
<script src="src/components/hello-world-with-params.js"></script>
<script>
function removeHelloWorld(){
console.log("Called!");
@@ -19,6 +27,11 @@
const helloElement = document.getElementsByTagName("hello-world")[0];
helloElement.parentNode.removeChild(helloElement);
}
function changeHelloWorldParam(){
const helloParamElement = document.getElementsByTagName("hello-world-with-params")[0];
document.getElementsByTagName("hello-world-with-params")[0].setAttribute("name", "plop");
}
</script>
</body>
</html>

View File

@@ -0,0 +1,23 @@
class HelloWorldWithParamsElement extends HTMLElement {
static get observedAttributes() {return ['name']; }
constructor(){
super()
this.innerHTML = `<h1>Hello default !</h1>`;
}
attributeChangedCallback(attributeName, oldValue, newValue, namespace){
if(attributeName === "name"){
console.log("Attribute name changed!");
this.innerHTML = `<h1>Hello ${newValue} !</h1>`;
}
else{
console.log("Unknown attribute " + attributeName + "changed");
}
}
}
window.customElements.define(
'hello-world-with-params',
HelloWorldWithParamsElement);