baconjs形式的可选字段

时间:2016-01-25 17:44:14

标签: javascript stream reactive-programming rxjs bacon.js

我在bacon.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)

1 个答案:

答案 0 :(得分:0)

使用当前代码,我必须在每个输入中键入内容。如果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(''))
)