domInput.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 () {
  26. const promise = new Promise( (resolve, _) => {
  27. this.listeners.push(resolve);
  28. this.el.focus();
  29. });
  30. return promise;
  31. }
  32. notifyInput (text) {
  33. this.listeners.forEach(resolve => resolve(text));
  34. this.listeners.splice(0, this.listeners.length);
  35. }
  36. cancelPendingInputRequests () {
  37. this.listeners.forEach(resolve => resolve(''));
  38. this.listeners.splice(0, this.listeners.length);
  39. }
  40. }