domInput.js 944 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 () {
  27. this.el.focus();
  28. }
  29. removeListener (listener) {
  30. const idx = this.listeners.indexOf(listener);
  31. if (idx)
  32. this.listeners.splice(idx, 1);
  33. }
  34. notifyInput (text) {
  35. this.listeners.forEach(l => {
  36. l.notify(text);
  37. })
  38. }
  39. }