Lukasz Lysik
Lukasz Lysik

Reputation: 10620

How to name this pattern? Does similar exist? Queue of triggered callback

I'll need your help to name or identify existing pattern like that. For the application I'm developing I need to create a queue of callbacks which are fired by an event. Once an event is triggered, consecutive callbacks that are added to the queue are fired immediately.

In the code it would like like that:

var queue = new TriggeredCallbackQueue();

queue.onTriggerOrNow(() => console.log('Callback 1')); 
// Nothing is logged to the console

queue.onTriggerOrNow(() => console.log('Callback 2'));
// Nothing is logged to the console

queue.trigger();    // 'Callback1' and 'Callback 2' are logged to console

queue.onTriggerOrNow(() => console.log('Callback 3'));  
// 'Callback 3' is logged to the console

queue.onTriggerOrNow(() => console.log('Callback 4'));  
// 'Callback 4' is logged to the console

Do you know if such pattern already exists and is classified anywhere? How would you name it? What do you think about TriggeredCallbackQueue name?

Upvotes: 1

Views: 49

Answers (1)

Oskar
Oskar

Reputation: 2607

I think it's Promise design pattern, with slightly changed API:

class TriggeredCallbackQueue {
  constructor() {
    this.promise = new Promise((res, rej) => {
      this._res = res;
      this._rej = rej;
    });
  }

  trigger() {
    this._res();
  }

  onTriggerOrNow(cb) {
    this.promise = this.promise.then(cb);
  }
}

var queue = new TriggeredCallbackQueue();

queue.onTriggerOrNow(() => console.log('Callback 1'));
// Nothing is logged to the console

queue.onTriggerOrNow(() => console.log('Callback 2'));
// Nothing is logged to the console

setTimeout(() => {
  queue.trigger(); // 'Callback1' and 'Callback 2' are logged to console
}, 2000);

setTimeout(() => {
  queue.onTriggerOrNow(() => console.log('Callback 3'));
  // 'Callback 3' is logged to the console

  queue.onTriggerOrNow(() => console.log('Callback 4'));
  // 'Callback 4' is logged to the console
}, 4000);

setTimeout(() => {
  queue.trigger(); // Nothing happens
}, 5000);

Upvotes: 1

Related Questions