O'Reilly logo

TypeScript: Modern JavaScript Development by Ivo Gabe de Wolff, Vilic Vane, Remo H. Jansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required