Skip to content

Instantly share code, notes, and snippets.

@shikaan shikaan/app.js
Last active Nov 11, 2018

Embed
What would you like to do?
Command Pattern in Frontend JavaScript
// Concrete Command
class OpenAlertCommand {
constructor(receiver) {
this.receiver = receiver
}
execute() {
this.receiver.alert('Gotcha!')
}
}
// Receiver
class Window {
alert(message) {
window.alert(message)
}
}
// Invoker
class Button {
constructor(label, command) {
this.label = label
this.command = command
this.node = document.createElement('button')
this.build()
}
build() {
this.node.innerText = this.label
this.node.onclick = () => this.onClickHandler()
}
onClickHandler() {
this.command.execute()
}
}
// Client
export class Application {
constructor(node) {
this.node = node
}
init() {
const receiver = new Window()
const command = new OpenAlertCommand(receiver)
const button = new Button('Submit', command)
this.node.appendChild(button.node)
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>UI Kit</title>
</head>
<body>
<main id="app"></main>
<script async src="./index.js"></script>
</body>
</html>
import {Application} from './app'
const appNode = document.getElementById('app')
const application = new Application(appNode)
application.init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.