createFieldsStore.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. class FieldsStore {
  2. constructor(fields = {}) {
  3. this.fields = fields
  4. }
  5. setFields(fields) {
  6. Object.assign(this.fields, fields)
  7. }
  8. updateFields(fields) {
  9. this.fields = fields
  10. }
  11. clearField(name) {
  12. delete this.fields[name]
  13. }
  14. getValueFromFields(name, fields) {
  15. const field = fields[name]
  16. if (field && 'value' in field) {
  17. return field.value
  18. }
  19. return field.initialValue
  20. }
  21. getAllFieldsName() {
  22. const { fields } = this
  23. return fields ? Object.keys(fields) : []
  24. }
  25. getField(name) {
  26. return {
  27. ...this.fields[name],
  28. name,
  29. }
  30. }
  31. getFieldValuePropValue(fieldOption) {
  32. const { name, valuePropName } = fieldOption
  33. const field = this.getField(name)
  34. const fieldValue = 'value' in field ? field.value : field.initialValue
  35. return {
  36. [valuePropName]: fieldValue,
  37. }
  38. }
  39. getFieldValue(name) {
  40. return this.getValueFromFields(name, this.fields)
  41. }
  42. getFieldsValue(names) {
  43. const fields = names || this.getAllFieldsName()
  44. return fields.reduce((acc, name) => {
  45. acc[name] = this.getFieldValue(name)
  46. return acc
  47. }, {})
  48. }
  49. resetFields(ns) {
  50. const { fields } = this
  51. const names = ns || this.getAllFieldsName()
  52. return names.reduce((acc, name) => {
  53. const field = fields[name]
  54. if (field) {
  55. acc[name] = field.initialValue
  56. }
  57. return acc
  58. }, {})
  59. }
  60. }
  61. export default function createFieldsStore(fields) {
  62. return new FieldsStore(fields)
  63. }