There are lots of examples of Rx.Observable.fromEvent(element, eventName)
using a jquery selection as the element to capture events from. However is it possible for Rx listen to only events from a filtered event setup with 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.
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? What's the best approach?
see http://jsfiddle.net/ktzk1bh3/2/
HTML:
<div class="aClass">
<div>
<a class="something">Click me</a>
</div>
</div>
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(
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.