cap:actions - emit events on actions

This capability is used when a thing support emitting events when an action such a button press occurs.

if(thing.matches('cap:actions')) {
        // This thing supports actions
        thing.on('action', action => console.log('Action occurred:', action);

        // Listen for a specific action
        thing.on('action:test', () => console.log('Test action occurred');
}

API

actions();()

Get the actions that the thing supports.

Returns:Promise that resolves to any array containing the actions as codes.

Example:

const actions = await thing.actions();

const action = actions[0];
console.log('First action id:', action.id);

Events

actionsChanged

The available actions have changed. Payload will be the same value that will be returned by the values attribute.

Example:

thing.on('actionsChanged', actions => console.log('Actions are now:', actions);
action

An action has occurred. The payload is an object with the keys:

  • action - the identifier of the action
  • data - optional data of the action

Example:

thing.on('action', e => console.log('Action', e.action, 'with data', e.data));
action:<id>

An action of type <id> has occurred. <id> will be a supported action, see the actions attribute for supported actions.

thing.on('action:test', () => console.log('Test action occurred'));

Protected methods

updateActions(actions)

Update the available actions.

Arguments:
  • actions (array) – The actions that this thing supports. Each item in the array will be converted to code.

Example:

this.updateActions([
        'button1',
        { id: 'button2', description: 'Optional description' },
        'button3: Description for button 3'
]);
emitAction(action[, data])

Emit an action with the given identifier. Optionally provide some extra data.

Arguments:
  • action (string) – The action that should be emitted.
  • data (mixed) – The optional data to include with the action event.

Example:

this.emitAction('button1');
this.emitAction('rotated', { amount: 45 });

Implementing capability

When implementing this capability updateActions need to be called with the available actions. When an action occurrs the method emitAction needs to be called.

Example:

const { Thing } = require('abstract-things');
const { Actions } = require('abstract-things/contollers');

class Example extends Thing.with(Actions) {
        initCallback() {
                return super.initCallback()
                        .then(() => this.updateActions(actionsDetected));
        }
}