All files / src tanokDispatcher.js

100% Statements 17/17
100% Branches 4/4
100% Functions 8/8
100% Lines 15/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x   46x 46x   86x 86x         1x   45x   45x   130x             45x                                       17x 17x 17x 17x 17x      
export const TanokDispatcher = function() {};
 
TanokDispatcher.prototype.collect = function () {
  return Object.keys(this.events).map(
    (handlerFuncName) => {
        const pair = this.events[handlerFuncName];
        return [pair[0], pair[1].bind(this)];
    }
  );
}
 
TanokDispatcher.prototype[Symbol.iterator] = function(){
  function makeIterator(array){
      var nextIndex = 0;
 
      return {
         next: function(){
             return nextIndex < array.length ?
                 {value: array[nextIndex++], done: false} :
                 {done: true};
         }
      };
  }
 
  return makeIterator(this.collect());
}
 
/**
 * Decorator used with TanokDispatcher
 *
 * Usage example:
 *
 * class HelloWorldDispatcher extends TanokDispatcher {
 *
 *   @on('helloEvent')
 *   helloWorld (eventPayload, state) {
 *     state.word = eventPayload.word;
 *     return [state, helloWorldEffect];
 *   }
 * }
 *
 * @param predicate - action title or multiple values like @on('actionTitle', debounce(500))
 * @returns {Function}
 */
export function on(...predicate) {
  return (target, property) => {
    target.events = target.events || {};
    const handlerFunc = target[property];
    target.events[property] = [predicate, handlerFunc];
  };
}