Reputation: 2835
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
Upvotes: 3
Views: 5480
Reputation: 3315
You were pretty close.
Refers to the API documentation for the fromEvent method, the third argument should be a function which can take arguments, and return a single object.
so you have to do :
Rx.Observable.fromEvent(li, 'click', _ => { return { src: elm.img } })
Then when you will subscribe to this, you will get an object with the src property.
Moreover, I have updated your code to make it in a functional way
const people = [
{ name: "Bert", img: "http://vignette1.wikia.nocookie.net/muppet/images/e/e1/Bert_smile.png/revision/latest?cb=20110630173259" },
{ name: "Enrie", img: "http://vignette1.wikia.nocookie.net/muppet/images/4/41/Ernie-RubberDuckie.jpg/revision/latest?cb=20110423180533" },
{ name: "Elmo", img: "https://upload.wikimedia.org/wikipedia/en/7/74/Elmo_from_Sesame_Street.gif" }
];
const ul = $('#list');
const clickStream = people.map((elm) => {
const li = $('<li />');
li.html(elm.name);
li.data('src', elm.img);
ul.append(li);
return Rx.Observable.fromEvent(li, 'click', _ => { return { src: elm.img } })
}).reduce((a, b) => Rx.Observable.merge(a, b), Rx.Observable.empty())
clickStream.subscribe(e => console.log(e))
Feel free to check the updated JsFiddle
Upvotes: 3
Reputation: 18665
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 }
}
});
Upvotes: 3