Skip to content

Commit

Permalink
Add pattern with this in action handler, from EventEmitter (#1664)
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowspawn committed Dec 25, 2021
1 parent 253f4ff commit c6e0ee8
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Readme.md
Expand Up @@ -535,6 +535,20 @@ program
});
```
If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).
Example file: [action-this.js](./examples/action-this.js)
```js
program
.command('serve')
.argument('<script>')
.option('-p, --port <number>', 'port number', 80)
.action(function() {
console.error('Run script %s on port %s', this.args[0], this.opts().port);
});
```
You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
```js
Expand Down
20 changes: 20 additions & 0 deletions examples/action-this.js
@@ -0,0 +1,20 @@
#!/usr/bin/env node

// This example is used as an example in the README for the action handler.

// const { Command } = require('commander'); // (normal include)
const { Command } = require('../'); // include commander in git clone of commander repo
const program = new Command();

program
.command('serve')
.argument('<script>')
.option('-p, --port <number>', 'port number', 80)
.action(function() {
console.error('Run script %s on port %s', this.args[0], this.opts().port);
});

program.parse();

// Try the following:
// node action-this.js serve --port 8080 index.js
10 changes: 10 additions & 0 deletions tests/command.action.test.js
Expand Up @@ -12,6 +12,16 @@ test('when .action called then command passed to action', () => {
expect(actionMock).toHaveBeenCalledWith(cmd.opts(), cmd);
});

test('when .action called then this is set to command', () => {
const program = new commander.Command();
let actionThis;
const cmd = program
.command('info')
.action(function() { actionThis = this; });
program.parse(['node', 'test', 'info']);
expect(actionThis).toBe(cmd);
});

test('when .action called then program.args only contains args', () => {
// At one time program.args was being modified to contain the same args as the call to .action
// and so included the command as an extra and unexpected complex item in array.
Expand Down

0 comments on commit c6e0ee8

Please sign in to comment.