Cycle.js 点击按钮获取输入值

Cycle.js getting input value on button click

我正在使用 Cycle.js 开发待办事项列表示例应用程序,我遇到了以下问题。我正在尝试在用户单击“添加”按钮时处理添加新的待办事项,效果很好,但另一方面,我有一个流提供文本输入更改事件,当与点击流结合使用时,它使我的应用程序添加新的待办事项即使在更改文本输入但未单击“添加”按钮的情况下,例如集中注意力。在这种情况下的方法是什么?我可以只删除 todoChange$ 流并直接从 addClick$ 流访问 DOM 吗,否则这将违反 Cycle.js 理念?

JS斌:https://jsbin.com/wugawaheni/edit?js,console,output

const xs = xstream.default;
const {div, input, p, makeDOMDriver} = CycleDOM;

const intent = (DOMSource) => {
  const addClick$ = DOMSource.select('.add').events('click').map(ev => true);
  const todoChange$ = DOMSource.select('.todo').events('change').map(ev => ev.target.value);

  return { addClick$, todoChange$ };
};

const model = (addClick$, todoChange$) => {
  const add$ = addClick$.startWith(false);
  const todo$ = todoChange$.startWith('');

  return xs.combine(add$, todo$)
    .map((combined$) => combined$[1])
    .fold((todos, todo) => {
      todo.trim() && todos.push(todo);
      return todos;
    }, []);
};

const view = state$ => state$.map(todos => div([
  input({attrs: {type: 'text', class: 'todo'}}),
  input({attrs: {type: 'submit', value: 'Add', class: 'add'}}),
  div(todos.map(todo => p(todo)))
]));


const main = (sources) => {
  const { addClick$, todoChange$ } = intent(sources.DOM);
  const state$ = model(addClick$, todoChange$);
  const vdom$ = view(state$);

   return {
     DOM: vdom$
   };
 };

Cycle.run(main, {
   DOM: makeDOMDriver('#app')
 });

包括xstream/extra/sampleCombine,然后...

变化:

//return xs.combine(add$, todo$)
return add$.compose(sampleCombine(todo$))

来自 sampleCombine 文档:

Marble diagram:

--1----2-----3--------4--- (source)
----a-----b-----c--d------ (other)
     sampleCombine

-------2a----3b-------4d--

在这种情况下,add$sourcetodo$other。结果流仅在 other 发出值时发出,并且在 source 发出值时发出。换句话说,如果 other 上有一个值可以与之结合,则流仅在 source 发出时发出。

注意:sampleCombine 未包含在默认 xstream 库中。

ESNextbin 演示。