Last active
November 11, 2018 08:14
-
-
Save shikaan/77367e98e41351549bec891fbf626b43 to your computer and use it in GitHub Desktop.
Command Pattern in Frontend JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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