1
0

domInput.js 994 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import {Input} from './input';
  2. export class DOMInput extends Input{
  3. constructor (element) {
  4. super();
  5. let id = element
  6. if(element[0] == '#') {
  7. id = element.substring(1);
  8. }
  9. this.el = document.getElementById(id);
  10. this.listeners = [];
  11. this.setupEvents();
  12. }
  13. setupEvents () {
  14. this.el.addEventListener('keydown', this.captureInput.bind(this));
  15. }
  16. captureInput (event) {
  17. const code = event.keyCode || event.which;
  18. if (code === 13) {
  19. let text = this.el.value;
  20. text = text.replace('[\n\r]+', '');
  21. this.notifyInput(text);
  22. this.el.value = "";
  23. }
  24. }
  25. requestInput (callback) {
  26. this.listeners.push(callback);
  27. this.el.focus();
  28. }
  29. notifyInput (text) {
  30. this.listeners.forEach(resolve => resolve(text));
  31. this.listeners.splice(0, this.listeners.length);
  32. }
  33. cancelPendingInputRequests () {
  34. this.listeners.forEach(resolve => resolve(''));
  35. this.listeners.splice(0, this.listeners.length);
  36. }
  37. }