saltyrtc / saltyrtc-client-js

SaltyRTC JavaScript implementation.
MIT License
29 stars 6 forks source link

Implement Event Handling #16

Closed dbrgn closed 8 years ago

dbrgn commented 8 years ago

As discussed in saltyrtc/saltyrtc-meta#34

interface Event {
    type: string,
    data: any,
}

type EventHandler = (ev: Event) => boolean | void;

// Register an event handler
on(event: string | string[], handler: EventHandler): void;

// Run an event handler only once
once(event: string | string[], handler: EventHandler): void;

// Cancel an event handler
off(event: string | string[], handler?: EventHandler): void;

Examples:

// Classic event handler
salty.on('connected', (event) => console.log('SaltyRTC is connected'));

// One-time event handler
salty.once('data', (event) => console.log('The first message arrived.'));

// Data event handler that can remove itself
salty.on('data', (event) => {
  if (event.data.dataType === 'panic') {
    console.error('everybody panic');
    return false;
  }
});

// Specialized event handler(s)
salty.on(['data:offer', 'data:answer'], (event) => {
  console.log('A', event.type, 'event is being handled');
  let dataMessage = event.data;
  console.info('Message', dataMessage.dataType, 'with value', dataMessage.data);
});

// Deregistration
function acceptPranswer(event) {
  console.log('pranswer arrived');
}
salty.on('data:pranswer', acceptPranswer);
salty.once('data:answer', (event) => {
  console.log('final answer arrived');
  // Don't accept pranswers anymore
  salty.off('data:pranswer', acceptPranswer);
});
dbrgn commented 8 years ago

Closed by #15.