03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 8<br />

■ ■ ■<br />

The Bridge Pattern<br />

In the world of API implementations, bridges are incredibly useful. In fact, they’re probably<br />

one of the most underused patterns. Of all patterns, this is the simplest to start putting into<br />

practice immediately. If you’re building a JavaScript API, this pattern can be used to ensure<br />

that the dependent classes and objects are coupled to it loosely. As defined by the Gang of<br />

Four, a bridge should “decouple an abstraction from its implementation so that the two can<br />

vary independently.” Bridges are very beneficial when it comes to event-driven programming,<br />

which is a style that is used often in JavaScript.<br />

If you’re just entering the world of JavaScript API development, you’re most likely going to<br />

be creating a lot of getters, setters, requesters, and other action-based methods. Whether<br />

they’re used to create a web service API or simple accessor and mutator methods, bridges<br />

will help you keep your API code clean come implementation time.<br />

Example: Event Listeners<br />

One of the most practical and frequent use cases for a bridge is event listener callbacks. Let’s<br />

say, for instance, that you have an API function called getBeerById, which returns data about<br />

a beer based on an identifier. Naturally, in any web application, you want this data to be fetched<br />

when a user performs an action (such as clicking an element). Most likely the element you click<br />

contains the beer identifier, either stored in the element ID itself, or in some other custom<br />

attribute. Here’s one way of doing it:<br />

addEvent(element, 'click', getBeerById);<br />

function getBeerById(e) {<br />

var id = this.id;<br />

asyncRequest('GET', 'beer.uri?id=' + id, function(resp) {<br />

// Callback response.<br />

console.log('Requested Beer: ' + resp.responseText);<br />

});<br />

}<br />

As you can see, this is an API that only works if it is run within the context of a browser.<br />

Naturally, due to the way event listener callbacks work, you get passed back an event object as<br />

the first argument. That’s useless in this case, and there is only the scope of callback to work<br />

with to grab that ID from the this object. Good luck running this against a unit test, or better<br />

109

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!