What is the Command pattern and where is it useful in JavaScript apps?
Short answer
Command encapsulates an action (and its parameters) as an object with a consistent execute() method, so actions can be queued, logged, undone, or passed around independently of the code that triggers them.
Advertisement
AModel answer
Command encapsulates an action (and its parameters) as an object with a consistent execute() method, so actions can be queued, logged, undone, or passed around independently of the code that triggers them.
class AddItemCommand {
constructor(cart, item) { this.cart = cart; this.item = item; }
execute() { this.cart.push(this.item); }
undo() { this.cart.pop(); }
}Real-world example
Implementing undo/redo functionality in a drawing or text-editing application.
Likely follow-ups
- How does Command relate to Redux-style actions and reducers?
Related topics