How to focus input using Cycle.js and RxJS?

How to focus input using a loop? Do I need to go into the DOM and invoke .focus()with or without jQuery, or is there another way with Cycle / RxJS?

+4
source share
3 answers

Yes , you need to get inside the DOM and invoke .focus()with or without jQuery. However, this is a side effect , and this Cycle.js convention transfers these kinds of side effects to the so-called driver .

The two questions a driver should know are:

  • which element do you want to focus?
  • ?

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 .

+6

, , . , . , , .

intent():

function intent(DOMSource) {
    const textStream$ = DOMSource.select('#input-msg').events('keyup').map(e => e.target);
    const buttonClick$ = DOMSource.select('#send-btn').events('click').map(e => e.target);

    return buttonClick$.withLatestFrom(textStream$, (buttonClick, textStream) => {
        return textStream;
    });
}

,

function main(sources) {
    const textStream$ = intent(sources.DOM);

    const sink = {
       DOM: view(sources.DOM),
       EffectLostFocus: textStream$,
    }

    return sink;
}

:

Cycle.run(main, {
    DOM: makeDOMDriver('#app'),
    EffectLostFocus: function(textStream$) {    
         textStream$.subscribe((textStream) => {
         console.log(textStream.value);
         textStream.focus();
         textStream.value = '';
      })
    }
});

codepen.

+5
+2
source

Source: https://habr.com/ru/post/1626280/


All Articles