Object Literal Delegates

Furthering on from my introduction tutorial to object literals in JavaScript, this is a slightly more advanced tutorial on how to set up delegates. A delegate is essentially a callback that one object can register for, usually receiving data from the object doing the delegating.

In this tutorial, you’ll learn how to:

  • Set up a method to add an infinite number of delegates
  • Set up a method to remove a delegate
  • Send messages to the delegates

Here’s a working example:

If the setup of the objects themselves is confusing then make sure you’ve read my introduction tutorial, but here’s a rundown of what I’ve done:

There are three objects here, the Map object and two other objects which will be a Map delegate. The Map object has a property called  delegates, which will hold an array of all the delegates you add. The Map object also has three methods: .addDelegate(), .removeDelegate() and .sendDataToDelegates(). These are all pretty self-explanatory.

The two delegate objects, MapDelegate and AnotherDelegate both have to implement  .coordinatesChanged() which is a required method because otherwise the script will break when Map tries to call it. You can make a method optional by first checking if it’s defined before calling it for each delegate.

As you can see, the delegate objects both implement the .coordinatesChanged() method, but they do different things with the data (one prints the coordinates to the console, the other alerts the user with a dialog). All they care about is that the coordinates have changed and what the new coordinates are, they do their own thing with the new data.