How can I have obervable and subscribers for multiple elements?

Delfin :

I have a table and many cells with input inside them

I want an event to be triggered and get the value on keyup, keydown and enter when any change is made in the input box.

Things I have tried include following in my js

var sources = document.querySelectorAll('td');

var source = Rx.Observable.fromEvent(sources, 'click');
Rx.Observable.fromEvent(sources,'click')
.map(v => {return v})
.subscribe(
    v => { console.log(v) },
    e => { console.log(e) },
    () => { console.log('complete') }
);

I am first time user of RxJs and dont understand why only the first cell can trigger the event and not other cells of table. How can I achieve events over all cells?

kctang :

try something like this:

    // get the sources into an array
    const sources = document.querySelectorAll('td')
    const sourcesArray = []
    sources.forEach(source => sourcesArray.push(source))

    // any even from the merged observables will emit a value...
    merge(
      // for each source, create an observable via fromEvent
      ...sourcesArray.map(source => fromEvent(source, 'click'))
    ).pipe(
      // ...value emitted can be from any of the merged observables (i.e. the fromEvent())
      // note: pipe() and tap() is optional...
      tap(val => console.log(`pipe an chain whatever you need here`))
    ).subscribe(val => console.log(`use next if u just need the next value... ${val}`))

FYI, i did not run the code, but the concept should be correct. Hope this helps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29971&siteId=1