Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HookRepository.ts « util « src - github.com/jsxc/jsxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 965a79d8a49ee40be869fd7ad2483baed285a9ba (plain)
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
export default class HookRepository<Args extends any[] = any[]> {
   private hooks = {};

   public registerHook(eventName: string, func: (...args: Args) => void) {
      if (!this.hooks[eventName]) {
         this.hooks[eventName] = [];
      }

      this.hooks[eventName].push(func);
   }

   public removeHook(eventName: string, func: (...args: Args) => void) {
      let eventNameList = this.hooks[eventName] || [];

      if (eventNameList.indexOf(func) > -1) {
         eventNameList = $.grep(eventNameList, function (i) {
            return func !== i;
         });
      }

      this.hooks[eventName] = eventNameList;
   }

   public trigger(targetEventName: string, ...args: Args) {
      let hooks = this.hooks;

      let eventNames = Object.keys(hooks);
      eventNames.forEach(function (eventName) {
         if (targetEventName === eventName || targetEventName.indexOf(eventName + ':') === 0) {
            let eventNameHooks = hooks[eventName] || [];
            eventNameHooks.forEach(function (hook) {
               hook.apply({}, args);
            });
         }
      });
   }
}