如何使用 Cycle 聚焦输入?我是否需要到达 DOM 内部并使用或不使用 jQuery 调用 .focus()
,或者是否有其他使用 Cycle/RxJS 的方法?
最佳答案
是,您确实需要到达 DOM 内部并使用或不使用 jQuery 调用 .focus()
。然而,这是一个副作用,Cycle.js 的惯例是将这些类型的副作用转移到所谓的 driver 中。 .
司机需要知道的两个问题是:
- 您想关注哪个元素?
- 什么时候你想聚焦元素?
这两个问题的答案都可以由单个 DOM 元素流 提供。
创建驱动
首先制作你的驱动程序。我们称它为 SetFocus
。我们将使它成为所谓的只读驱动程序。它将从应用程序的接收器中读取,但不会向应用程序提供源。因为它是读取,所以驱动程序的函数需要接受一个形式参数,它将是一个流,称它为elem$
:
function makeSetFocusDriver() {
function SetFocusDriver(elem$) {
elem$.subscribe(elem => {
elem.focus();
});
}
return SetFocusDriver;
}
此驱动程序获取到达流中的任何 DOM 元素并对其调用 .focus()
。
使用驱动程序
将其添加到提供给 Cycle.run
函数的驱动程序列表中:
Cycle.run(main, {
DOM: makeDOMDriver('#app'),
SetFocus: makeSetFocusDriver() // add a driver
});
然后在你的主函数中:
function main({DOM}) {
// setup some code to produce the elem$ stream
// that will be read by the driver ...
// [1]: say _when_ we want to focus, perhaps we need to focus when
// the user clicked somewhere, or maybe when some model value
// has changed
// [2]: say _what_ we want to focus
// provide the textbox dom element as actual value to the stream
// the result is:
// |----o-----o-----o--->
// where each o indicates we want to focus the textfield
// with the class 'field'
const textbox$ = DOM.select('.field').observable.flatMap(x => x); // [2]
const focusNeeded = [
clickingSomewhere$, // [1]
someKindofStateChange$ // [1]
];
const focus$ = Observable.merge(...focusNeeded)
.withLatestFrom(textbox$, (_, textbox) => textbox); // [2]
// ...
// [*]: Add driver to sinks, the driver reads from sinks.
// Cycle.js will call your driver function with the parameter
// `elem$` being supplied with the argument of `focus$`
return {
DOM: vtree$,
SetFocus: focus$, // [*]
};
}
然后您可以配置 focusNeeded
来说明您希望何时聚焦 .field
。
关于javascript - 如何使用 Cycle.js 和 RxJS 聚焦输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35051281/