Command Pattern

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 ...

Get TypeScript Design Patterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.