我如何拥有多个元素的可观察对象和订阅者?

问题描述 投票:1回答:1

我有一个表和许多个单元格,其中有输入内容

我希望事件被触发,并在输入框中进行任何更改时获取键,键按下并输入的值。

我尝试过的东西包括以下我的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') }
);

我是RxJ的首次用户,不理解为什么只有第一个单元格可以触发事件,而表的其他单元格却不能。如何在所有单元上实现事件?

javascript html dom ecmascript-6 rxjs
1个回答
0
投票

尝试这样的事情:

    // 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}`))

仅供参考,我没有运行代码,但是这个概念应该是正确的。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.