dthree / vorpal

Node's framework for interactive CLIs
http://vorpal.js.org
MIT License
5.63k stars 278 forks source link

prompt is not working. this is undefined in action #298

Closed paustria closed 6 years ago

paustria commented 6 years ago

For some reason, this.prompt doesn't work.

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

  vorpal
  .command('test', 'test')
  .action((args, callback) => {
    console.log('this', this, args, callback);
    callback();
  });

vorpal
  .delimiter('test-app$')
  .show();

Here is my console.log. this is undefined.

this undefined { options: { select: true } } function () {
    var argus = util.fixArgsForApply(arguments);
    onCompletion(wrapper, argus[0], argus[1], argus);
  }

Do you I need to add anything else to make this exposes to every action?

danielhickman commented 6 years ago

You used an arrow function so you wouldn't be using the this value of the vorpal.action callback function. Is that intended?

paustria commented 6 years ago

@danielhickman Ahhh....You are correct. If I would like to use arrow function, how can I pass this to action? I prefer to use es6/es7 pattern.

danielhickman commented 6 years ago

@paustria I don't think of arrow functions as a replacement for regular functions and the syntax wouldn't be shorter or less confusing to work around it.

A common pattern would be to use a variable named self or something, but you have to get passed the this value to begin. Maybe somewhere you could store the result of some call to vorpal, but I don't see a result that would get you a command instance. vorpal.command() and vorpal.action() return an instance of Command instead (different, but related).

I'd recommend using function(){} when you need this or arguments.

paustria commented 6 years ago

@danielhickman Thank you for the help. I will close this issue.