Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Design Pattern: Simple Mediator

    Brett CassetteBrett Cassette

    In this video Brett shows us how to create a simple mediator for cleanly separating concerns within your application. This is the first in a series that will build a robust, fully tested mediator for events in your AngularJS application.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Brett Shollenberger: Today we're going to talk about the mediator pattern which works really great in JavaScript because it's an event driven language. We're going to use rootScope emit here to send out events and then we're going to listen for them in the run block. We're going to use rootScope on down in the run block to listen for the same event that we sent out to the system.

    Whenever this event is heard it's going to fire this callback here which will pass in the event and the order that it heard. And then will, in that new callback, create an email and will send that email to the user. This is really great because it allows our order to know nothing about the fact that it creates emails.

    But we don't want it to actually know about rootScope. We don't want to pass it in as a dependency because it has a lot of other functionality we don't want to give it access to. We're just going to wrap rootScope emit in this emit factory and we'll give it access to that instead.

    Here we'll just pass in instead of rootScope emit and then down here we'll use emit the same way.

    And so, when we save this out we can see that when we place new orders that we get those emails. Again, this is great because it allows our order to follow the single responsibility principle really, really well. The run block handles all the logic when it gets created.

    Again, this is a really simple mediator. In later videos we'll show you more advanced logic. This should get you started.