Skip to content

Instantly share code, notes, and snippets.

@MouseZero
Last active November 13, 2018 02:51
Show Gist options
  • Save MouseZero/b2d260c58b482eb2043dd9d930f5c964 to your computer and use it in GitHub Desktop.
Save MouseZero/b2d260c58b482eb2043dd9d930f5c964 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Component Functions</title>
</head>
<body>
<my-component></my-component>
</body>
<script>
function globalFunction() {
alert('from global function')
}
class MyComponent extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({mode: 'open'})
shadow.appendChild(this.globalButton())
shadow.appendChild(this.parentButton())
shadow.appendChild(this.localButton())
shadow.parentFunction = () => alert('from parent function')
}
globalButton() {
const button = document.createElement('button')
button.setAttribute('onclick', 'globalFunction()')
button.textContent = 'Global Button'
return button
}
parentButton() {
const button = document.createElement('button')
button.setAttribute('onclick', "console.log(this.parentNode.parentFunction())")
button.textContent = 'Parent Button'
return button
}
localButton() {
const button = document.createElement('button')
button.setAttribute('onclick', "this.localFunction()")
button.textContent = 'Local Button'
button.localFunction = () => alert('from local function')
return button
}
}
customElements.define('my-component', MyComponent)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment