
TypeScript Design Patterns
By :

Command Pattern involves encapsulating operations as executable commands and could either be in the form of objects or functions in JavaScript. It is common that we may want to make operations rely on certain context and states that are not accessible for the invokers. By storing those pieces of information with a command and passing it out, this situation could be properly handled.
Consider an extremely simple example: we want to provide a function called wait
, which returns a cancel
handler:
function wait() { let $layer = $('.wait-layer'); $layer.show(); return () => { $layer.hide(); }; } let cancel = wait(); setTimeout(() => cancel(), 1000);
The cancel
handler in the preceding code is just a command we were talking about. It stores the context ($layer
) using closure and is passed out as the return value of function wait
.
Closure in JavaScript provides a really simple way to store command context and states, however, the direct...