Check out a free preview of the full Rx.js Fundamentals course

The "fromEvent Solution" Lesson is part of the full, Rx.js Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

Steve walks through the solution to the fromEvent exercise.


Transcript from the "fromEvent Solution" Lesson

>> So, yeah, super straightforward. Our job is to find the button, create an observable from the button, subscribe it to the button. And then upon subscribing, whenever we hear an event, add a very simple notification to the DOM. So, we know that from event. Can take an HTML element and then what we wanna listen for.

Now the interesting part here is just like an event listener will theoretically retrofitted to the event whether or not you store in a variable or not, and then you have to do all that stuff like cool. If you ever want to remove that event listener, you better have stored that function into a variable, so then you can remove the reference to that function from the event listener, so on and so forth, right?

From event seeks to protect you from all of that fun stuff with event listeners and kind of encapsulate that. So now you can create your stream. You can subscribe and unsubscribe as its own separate, then you'll get back an object that will allow you to unsubscribe so on and so forth.

So here, we'll say, I'll call button clicks, that seems like a really good name for this observable. And so what we'll say is, we'll subscribe to it in this case. So button clicks, and will subscribe. And we'll say, when that happens, we want to add the message to the Dom.

Cool, all right, and so let's just make sure that, that works. So we'll go here to generate observables from events except I will use the one that is local cuz I use production 1, what's gonna happen and we can see, we get what we think we're gonna get here which is when the click happens, it will go ahead and run the listener, right?

We could theoretically take this and do other things with it as well. So if we wanted to go in here and we wanted to say, okay, not only that, but I would also, log it to the console or we could even alert, yeah, let's alert, why not. Alright, so we have one stream of events happening and then we can subscribe 2 to multiple things in this case.

So now we'll go ahead, we'll refresh, you can see that I get the alert and also I get the notification on the page as well. So as a bunch of other things that we'll do as time goes on like clearly the ability to click buttons and interact with the UI is a thing that is kind of core to what we all do, building user interfaces.

So we will kind of play with this more in a little bit. But right now, we're kind of just building up that tool set of fundamentals in this case.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now