Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import {Inject, Injectable} from '@angular/core';
  2. import {EventManager} from '@angular/platform-browser';
  3. import {DOCUMENT} from '@angular/common';
  4. import {Observable} from 'rxjs';
  5.  
  6.  
  7. type Options = {
  8. element: any;
  9. keys: string;
  10. }
  11.  
  12. @Injectable({
  13. providedIn: 'root'
  14. })
  15. export class HotkeysService {
  16.  
  17. private subscriptions: Map<string, Subscription> = new Map<string, Subscription>();
  18.  
  19. defaults: Partial<Options> = {
  20. element: this.document
  21. };
  22.  
  23. constructor(private eventManager: EventManager,
  24. @Inject(DOCUMENT) private document: Document) { }
  25.  
  26. addShortcut(options: Partial<Options>) {
  27. const merged = { ...this.defaults, ...options };
  28. const event = `keydown.${merged.keys}`;
  29.  
  30. const observable = new Observable(observer => {
  31. const handler = (e) => {
  32. e.preventDefault();
  33. observer.next(e);
  34. };
  35.  
  36. const dispose = this.eventManager.addEventListener(
  37. merged.element, event, handler
  38. );
  39.  
  40. return () => {
  41. dispose();
  42. };
  43. })
  44. this.subscriptions.set(event, observable);
  45. return observable;
  46. }
  47.  
  48. removeShortcut(options: Partial<Options>){
  49. const subscription = this.subscriptions.get(`keydown.${options.keys}`);
  50. if(subscription != null){
  51. subscription.unsubscribe();
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement