Skip to content

Instantly share code, notes, and snippets.

@shikaan
Last active November 11, 2018 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shikaan/77367e98e41351549bec891fbf626b43 to your computer and use it in GitHub Desktop.
Save shikaan/77367e98e41351549bec891fbf626b43 to your computer and use it in GitHub Desktop.
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