control.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const defaultOption = {
  2. valueKey: 'value',
  3. defaultValueKey: 'defaultValue',
  4. changeEventName: 'change',
  5. strict: true,
  6. };
  7. function useControl(option = {}) {
  8. const { valueKey, defaultValueKey, changeEventName, strict } = Object.assign(Object.assign({}, defaultOption), option);
  9. const props = this.properties || {};
  10. const value = props[valueKey];
  11. const defaultValue = props[strict ? defaultValueKey : valueKey];
  12. let controlled = false;
  13. if (strict && typeof value !== 'undefined' && value !== null) {
  14. controlled = true;
  15. }
  16. const set = (newVal, extObj, fn) => {
  17. this.setData(Object.assign({ [`_${valueKey}`]: newVal }, extObj), fn);
  18. };
  19. return {
  20. controlled,
  21. initValue: controlled ? value : defaultValue,
  22. set,
  23. get: () => {
  24. return this.data[`_${valueKey}`];
  25. },
  26. change: (newVal, customChangeData, customUpdateFn) => {
  27. this.triggerEvent(changeEventName, typeof customChangeData !== 'undefined' ? customChangeData : newVal);
  28. if (controlled) {
  29. return;
  30. }
  31. if (typeof customUpdateFn === 'function') {
  32. customUpdateFn();
  33. }
  34. else {
  35. set(newVal);
  36. }
  37. },
  38. };
  39. }
  40. export { useControl };