Check out a free preview of the full A Tour of JavaScript & React Patterns course:
The "Observer Pattern Solution" Lesson is part of the full, A Tour of JavaScript & React Patterns course featured in this preview video. Here's what you'd learn in this lesson:

Lydia codes the solution to the Observer Pattern challenge.

Get Unlimited Access Now

Transcript from the "Observer Pattern Solution" Lesson

>> All right, so the first thing I'm gonna do is to create a new file called observable. And in here first we're just going to create an empty array with the observers. And then we're just going to experts and Objects. Now I'm just going to freeze it. You don't have to, I just like to do that to make sure that we don't accidentally change it.

[00:00:22] And the first method that we wanna add is to subscribe. So this one takes a function and we are pushing that function to the observers array. And then the second one is notify. And in this one we have the data and we want to notify all the observers within this array.

[00:00:36] So we can do observer stuff for each observer. And we invoke these observers with the data. Now we can import this observable, for example, in the NRES, so we can use, I'm just going to change this real quick. Us import Observable, from observable. And instead of invoking these methods I can say, Observable.notify data.

[00:01:04] And same for the other one. Now the only thing I have to change here is in analytics I also have to import this observable, so import Observable from observable. And here I just have to subscribe these methods because we want to invoke these methods when we notify them, are the observable.

[00:01:23] So Observable.subscribe since you analytics Observable.subcribe, custom analytics, and then Observable.subscribe, sendtoEmail. Subscribe, all right, so right now when we click on the button, the observable gets notified with the data that we pass here. So let's see if our observer is that a function? Let me just refresh this real quick.

[00:01:55] Yeah, so this was just stackless thing, I have to refresh it so the error goes away. But now when we invoke the observer, you can see that it has the exact same results. We log data to this fake analytics provider. But instead of invoking all these methods here on the event listener we just have to say observable.notify.