domInput.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import {Input} from './input';
  2. import $ from 'jquery';
  3. export class DOMInput extends Input{
  4. constructor (element) {
  5. this.el = $(element);
  6. this.listeners = [];
  7. this.setupEvents();
  8. }
  9. setupEvents () {
  10. this.el.on('keydown', (e) => {
  11. const code = e.keyCode || e.which;
  12. if (code === 13) {
  13. let text = this.el.val();
  14. text = text.replace('[\n\r]+', '');
  15. this.notifyInput(text);
  16. this.el.val('');
  17. }
  18. });
  19. }
  20. registerListener (listener) {
  21. if(!listener.notify) {
  22. throw new Error("InternalError: Input listener must implement a notify function.");
  23. }
  24. this.listeners.push(listener);
  25. }
  26. requestInput (callback) {
  27. this.listeners.push(callback);
  28. this.el.focus();
  29. }
  30. removeListener (listener) {
  31. const idx = this.listeners.indexOf(listener);
  32. if (idx)
  33. this.listeners.splice(idx, 1);
  34. }
  35. notifyInput (text) {
  36. this.listeners.forEach(resolve => {
  37. resolve(l);
  38. })
  39. this.listeners.splice(0, this.listeners.length);
  40. }
  41. }