qiniu / formstate-x

Manage state of form with ease.
https://qiniu.github.io/formstate-x
MIT License
33 stars 10 forks source link

`onChange()` for `FormState` #54

Closed nighca closed 2 years ago

nighca commented 2 years ago

Fix #40, detail: https://github.com/qiniu/formstate-x/issues/40#issuecomment-841190889

1. Method onChange for FormState (& ArrayFormState)

// for FormState
const state = new FormState({
  foo: new FielState(1),
  bar: new FieldState(2)
})
state.onChange({ foo: 3, bar: 4 })
state.value // { foo: 3, bar: 4 }

// for ArrayFormState:
const state = new ArrayFormState([1, 2], v => new FieldState(v))
state.onChange([3, 4])
state.value // [3, 4]

2. Methods (remove, insert, append, move) for ArrayFormState

const state = new ArrayFormState(['a', 'b', 'c', 'd'], v => new FieldState(v))

state.remove(from, num) // remove items from specific index
state.remove(1, 2) // [a, b, c, d] => [a, d]

state.insert(from, ...items) // insert items from specific index
state.insert(0, 'e', 'f') // [a, b, c, d] => [e, f, a, b, c, d]

state.append(...items) // insert items at the end of current field list, shorthand for `state.insert(state.$.length, ...items)`
state.append('e', 'f') // [a, b, c, d] => [a, b, c, d, e, f]

state.move(from, to) // move item, with specific from index and target index
state.move(0, 2) // [a, b, c, d] => [b, c, a, d]

3. Make FormState (& ArrayFormState) fields readonly

Manipulating fields object (or array) $ in native way is not allowed any more. It's now impossible to do things like:

// for FormState
state.$.foo = ... // assignment to property

// for ArrayFormState:
state.$[1] = ...  // assignment to index
state.$.push(...) // array methods which causes mutation

If you want to do fields' manipulation, use methods provided above. Which means, you don't need to care about sub fields' creation & disposition any more, formstate-x takes care of it.

lzfee0227 commented 2 years ago

need more demos / cases?

  1. arrayFormState.onChange or arrayFormState.move/remove/insert/append? (index / ref)
  2. new ArrayFormState(list.map(() => new ArrayFormState())).set/reset/onChange() ?
nighca commented 2 years ago

need more demos / cases?

@lzfee0227 是指这个 PR 的说明还是指 formstate-x 本身需要 demo?

nighca commented 2 years ago

看起来没有大的问题,这里先 merge(到 v3.x 分支),有后续问题可以在 v3.x 合并到 master 的时候再处理

lzfee0227 commented 2 years ago

是指这个 PR 的说明还是指 formstate-x 本身需要 demo

不是一个意思吗? 不是在这里写一下,然后最后 copy 到 formstate-x 相关文档里?

nighca commented 2 years ago

不是一个意思吗? 不是在这里写一下,然后最后 copy 到 formstate-x 相关文档里?

不着急,文档或者 demo 在 v3 最后补;后边 API 名、接口细节大概率还会调整,现在写了,回头也没法 copy 直接用的