You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.8 KiB

4 years ago
  1. (function($K)
  2. {
  3. $K.add('module', 'combobox', {
  4. init: function(app, context)
  5. {
  6. this.app = app;
  7. this.$win = app.$win;
  8. // defaults
  9. var defaults = {
  10. placeholder: ''
  11. };
  12. // context
  13. this.context = context;
  14. this.params = context.getParams(defaults);
  15. this.$element = context.getElement();
  16. },
  17. start: function()
  18. {
  19. this._buildSource();
  20. this._buildCaret();
  21. this._buildEvent();
  22. },
  23. stop: function()
  24. {
  25. this.$sourceBox.after(this.$element);
  26. this.$sourceBox.remove();
  27. this.$element.off('.kube.combobox');
  28. this.$win.off('.kube.combobox');
  29. },
  30. // private
  31. _buildSource: function()
  32. {
  33. this.$sourceBox = $K.dom('<div>');
  34. this.$sourceBox.addClass('combobox');
  35. this.$source = $K.dom('<input>');
  36. this.$source.attr('type', 'text');
  37. this.$source.attr('placeholder', this.params.placeholder);
  38. this.$sourceBox.width(this.$element.width());
  39. this.$sourceBox.append(this.$source);
  40. this.$element.after(this.$sourceBox);
  41. this.$element.attr('class', '');
  42. this.$element.attr('style', '');
  43. this.$sourceBox.append(this.$element);
  44. this.$win.on('resize.kube.combobox', this._resize.bind(this));
  45. },
  46. _buildCaret: function()
  47. {
  48. this.$sourceCaret = $K.dom('<span>');
  49. this.$sourceCaret.addClass('combobox-caret');
  50. this.$sourceBox.append(this.$sourceCaret);
  51. },
  52. _buildEvent: function()
  53. {
  54. this.$element.on('change.kube.combobox', this._select.bind(this));
  55. this.$source.on('keyup.kube.combobox', this._type.bind(this));
  56. },
  57. _resize: function()
  58. {
  59. this.$sourceBox.width(this.$element.width());
  60. },
  61. _type: function(e)
  62. {
  63. var value = this.$source.val();
  64. this.app.broadcast('combobox.set', this, value);
  65. if (this.$sourceValue) this.$sourceValue.remove();
  66. if (value.trim() === '') return;
  67. this.$sourceValue = $K.dom('<option>');
  68. this.$sourceValue.attr('value', value);
  69. this.$sourceValue.attr('selected', true);
  70. this.$sourceValue.text(value);
  71. this.$sourceValue.addClass('is-hidden');
  72. this.$element.append(this.$sourceValue);
  73. },
  74. _select: function(e)
  75. {
  76. var el = e.target;
  77. var value = el.options[el.selectedIndex].text;
  78. if (this.$sourceValue) this.$sourceValue.remove();
  79. this.$source.val(value);
  80. this.app.broadcast('combobox.set', this, value);
  81. }
  82. });
  83. })(Kube);