Skip to content

Docs | Using Arrow Functions

Jonathan Boiser edited this page Jun 26, 2016 · 1 revision

See this issue for more context.

Most of the code examples use the const self = this trick to bind callbacks to the context of the current command:

const vorpal = require('vorpal')();

vorpal
  .command('order pizza')
  .option('--anchovies')
  .action(function (args, cb) {
    const self = this; <---
    this.prompt({
      type: 'input',
      name: 'time',
      message: 'When would you like your pizza?',
    }, function (result) {
      self.log(`Okay, ${result.time} it is!`);
      cb();
    });
  });

But if you try to replace the callbacks to .action() with an arrow functions, you don't get this binding automatically:

const vorpal = require('vorpal')();

vorpal
  .command('order pizza')
  .option('--anchovies')
  .action((args, cb) => {
    this.prompt({ // error
      type: 'input',
      name: 'time',
      message: 'When would you like your pizza?',
    }, (result) => {
      this.log(`Okay, ${result.time} it is!`); // ditto
      cb();
    });
  });

If you try to run this, you will get a runtime exception complaining that this.prompt is not a function. With the arrow function, this does not bind to the context of the current action!

To get around this, the vorpal.activeCommand object was exposed, which gives you access to vorpal functions where this is bound to the context of the active command:

const vorpal = require('vorpal')();

vorpal
  .command('order pizza')
  .option('--anchovies')
  .action((args, cb) => {
    vorpal.activeCommand.prompt({
      type: 'input',
      name: 'time',
      message: 'When would you like your pizza?',
    }, (result) => {
      vorpal.activeCommand.log(`Okay, ${result.time} it is!`);
      cb();
    });
  });
Clone this wiki locally