Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Observable.fromEvent data

How can I attach event data to a Observable.fromEvent?

In my example I have the following array of objects

var people = [
    { name: "Bert", img: "" },
    { name: "Enrie", img: "" },
    { name: "Elmo", img: "" }
];

I want to create a clickStream with a data.src something like:

clickStream = Rx.Observable.fromEvent(li, 'click', { src :  people[p].img });

And then subscribe to it:

clickStream.subscribe(function(event) {
    $('#img')[0].src = event.data.src;
});

API documentation for fromEvent method

Edit

I created a JsFiddle of my example, note in the console log the event has a data object which is undefined - How do I assign it?

Note: I am not using a event emitter but a native DOM event

like image 455
Luke T O'Brien Avatar asked Feb 11 '26 11:02

Luke T O'Brien


1 Answers

I am not sure if I understood properly your use case, but if you want to add something to the event object passed by the listener, then just do it with a map :

clickStream = Rx.Observable.fromEvent(li, 'click').map(function (event){
  return {
    event : event,
    data : { src :  people[p].img }
  }
});

This in particular will be better than inserting directly the data property in the event. event should be inmutable.

Or you could use the selector overload (to test, never actually used that selector function):

clickStream = Rx.Observable.fromEvent(li, 'click', function (event){
  return {
    event : event,
    data : { src :  people[p].img }
  }
});
like image 71
user3743222 Avatar answered Feb 14 '26 01:02

user3743222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!