简体   繁体   English

如何设置Rx.Observable.fromEvent以使用jQuery过滤事件

[英]How to setup Rx.Observable.fromEvent to work with jQuery filtered events

There are lots of examples of Rx.Observable.fromEvent(element, eventName) using a jquery selection as the element to capture events from. Rx.Observable.fromEvent(element, eventName)有很多示例, Rx.Observable.fromEvent(element, eventName)示例使用jquery选择作为捕获事件的元素。 However is it possible for Rx listen to only events from a filtered event setup with jQuery? 但是,Rx是否有可能仅使用jQuery筛选的事件设置来侦听事件?

//Bind the event on body but only respond to events that match the filter
$('body').on('click', '.aClass div .something', function () {...});

//Bind to 'body' but only respond to events from the binding above
Rx.Observable.fromEvent(/*something here?*/);

I have come up with something effectively similar but it seems like it would be much more costly than the jquery filter. 我想出了一些实际上相似的东西,但是看起来比jquery过滤器要昂贵得多。

Rx.Observable.fromEvent($('body'), 'click')
.filter(function (e) {
  return $(e.target).is('.aClass div .something');
})
.subscribe(function () {...});

Is there some way I could turn the jQuery binding into an emitter and use that event stream with Rx? 有什么办法可以将jQuery绑定转换为发射器,并在Rx中使用该事件流? What's the best approach? 最好的方法是什么?

see http://jsfiddle.net/ktzk1bh3/2/ 看到http://jsfiddle.net/ktzk1bh3/2/

HTML: HTML:

<div class="aClass">
    <div>
        <a class="something">Click me</a>
    </div>
</div>

Javascript: Javascript:

//Bind to 'body' but only respond to events from the binding above
var source = Rx.Observable.create(function(o) {
    $('body').on('click', '.aClass div .something', function(ev) {
        o.onNext(ev);
    })
});

var sub = source.subscribe(function(ev) { console.log("click", ev) });

You can use Rx.Observable.fromEventPattern . 您可以使用Rx.Observable.fromEventPattern

Rx.Observable.fromEventPattern(
  function add(handler) {
    $('body').on('click', '.aClass div .something', handler);
  },
  function remove(handler) {
    $('body').off('click', '.aClass div .something', handler);
  }
);

This way it will automatically remove event handler on unsubscribe from observable subscription. 这样,它将自动取消可观察订阅中取消订阅的事件处理程序。

<div class='radios'>
  <input type='radio' name='r' value='PM'>PM
  <input type='radio' name='r' value='PCE'>PCE
  <input type='radio' name='r' value='PCS'>PCS
</div>
<textarea class='textarea'>

</textarea>

Rx.Observable.fromEvent(document.querySelector('.radios'),'click')
.subscribe((e)=>console.log(e.target.value));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM