培根格式的可选字段

Optional fields in baconjs form

本文关键字:字段 格式      更新时间:2023-09-26

我正在培根中构建可定制的表单.js。我对可能为空的可选字段有问题,例如电话有时是必需的,有时是可选的。

field_events = _.merge(
  _.mapValues(@form, @_build_field_streams), dynamic_field_events
)
valid_streams = _.pluck(_.values(field_events), 0)
all_invalid = Bacon.all(valid_streams).not().toProperty()
data_prop = Bacon.combineTemplate(
  _.mapValues(field_events, ([is_valid, value_stream]) -> value_stream)
)
submit_stream = @$el
  .asEventStream('click', @submit_selector)
  .doAction(".preventDefault")
  .alwaysSkipWhile(all_invalid)
@actions = Bacon.when(
  [data_prop, submit_stream],
  (data) -> {action: 'submit', param: data}
)

data_prop是延迟评估的,因此如果电话流没有任何值,我们将不会提交表单。有没有办法给流一个默认值或过滤combineTemplate中的空流?

其余代码:

_build_field_streams: ({selector, validator}, field) =>
value_stream = Bacon.mergeAll(
  @_get_field_change_streams(selector)
).map((e) ->
  $(e.currentTarget).val()
)
if _.isString validator
  validator = exports.validators[validator]()
# optional field are valid by default and for empty values
is_optional_field = field not in @mandatory_field
curr_validator = validator || @noop_validator
validator_fun = (x) -> if is_optional_field and not x
  return true
else
  return curr_validator(x)
validator_stream = value_stream.map(validator_fun)
is_valid = validator_stream.map(_.isEmpty).toProperty(is_optional_field).log('field')
[ok_events, bad_events] = validator_stream.split(_.isEmpty)
bad_events = bad_events.debounce(@invalid_delay)
defocus = @$el.asEventStream('blur', selector)
# TODO: Might be good to instantly go bad _if_ it was already valid.
Bacon.when(
  [ok_events],            true
  [is_valid, bad_events], ((valid) -> valid),
  [is_valid, defocus],    ((valid) -> valid)
).onValue( (valid) =>
  if valid
    @render_field_valid(selector)
  else
    @render_field_invalid(selector)
)
return [is_valid, value_stream]
_get_field_change_streams: (selector) ->
  # Hopefully these 2 cover most things.  Can always add more if we need.
  return _.map ['change', 'keyup'], (handler) =>
    @$el.asEventStream(handler, selector)

使用当前代码,我必须在每个输入中键入一些内容。我的理解是Bacon.when( [data_prop, submit_stream]如果data_prop是非空属性并且我们收到submit_stream事件,则会触发。为什么不评估data_prop?我相信Bacon.combineTemplate不会创建一个有价值的属性,除非所有value_stream都有一个事件。

我将流转换为具有默认值的道具

data_prop = Bacon.combineTemplate(
  _.mapValues(field_events, ([is_valid, value_stream]) -> value_stream.toProperty(''))
)