2

Handling events that bubble consists of creating an observable of the events on the top most element and filtering the stream, e.g.

let view,
    formView;

formView = (count, query) =>
    <form id='search-form'>
        <input type='text' id='query' />
        <div>count: {count}, query: {query}</div>
    </form>;

view = () => {
    let input,
        count = 0;

    input = Observable
        .fromEvent(document, 'keyup')
        .filter(e => e.target.id === 'query');

    return input
        .map((e) => {
            return formView(++count, e.target.value);
        })
        .startWith(formView(0));
}

I do not understand how to subscribe to an event that does not bubble, e.g. "focus"

input = Observable
        // event 'focus' does not bubble to the document
        .fromEvent(document, 'focus')
        .filter(e => e.target.id === 'query');

I cannot do:

input = Observable
    .fromEvent(document.querySelector('#query'), 'focus')
    [..]

because at the time the code is executed, #query element does not exist.

Gajus
  • 69,002
  • 70
  • 275
  • 438
  • Did you try to create the Observable in a `window.onload` handler? – Reto Aebersold Aug 03 '15 at 15:07
  • @RetoAebersold That would not change anything, because it is Rx observer that generates the DOM. Therefore, until the element exists it cannot attach the binding directly to the element. Unless of course, there was a way to make `focus` event bubble. – Gajus Aug 03 '15 at 15:30

1 Answers1

1

To answer the question in your comment about bubbling focus, use focusin event instead. It bubbles. Use this polyfill for Firefox.

To answer your primary question, you'd need to call fromEvent each time you produced a new DOM element. It is hard to show exact code, since the code you have wouldn't make sense - (when the element receives focus, recreate the element??). But it might look something like:

var focusEvent = view()
    .flatMapLatest(v => Rx.Observable.fromEvent(v.children[0], 'focus'));
Brandon
  • 38,310
  • 8
  • 82
  • 87
  • You made a good point. Most events that do not bubble (http://stackoverflow.com/a/31802555/368691) would not make sense in this scenario, i.e. you would not want to re-render the element. – Gajus Aug 04 '15 at 06:57