CHAPTER 15 Ensuring Correct Implementation of Chainable Methods

WHAT’S IN THIS CHAPTER?            

  • Using chainable methods to create more elegant code
  • Using test-driven development to implement chainable methods
  • Writing DRY unit tests to verify that methods are chainable
  • Showing how the then method of ECMAScript 6 promises enables chaining

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com/go/reliablejavascript on the Download Code tab. The files are in the Chapter 15 download and individually named according to the filenames noted throughout this chapter.

Does the structure and syntax of the following JavaScript statement look familiar?

$;("#myDiv").text("JavaScript").removeClass("unreliable") .addClass("reliable");

If you’ve done any client-side development since 2008 or so, chances are the answer is “Yes.” The statement is written using jQuery, a popular client-side JavaScript framework that’s used by over 52 million websites on the Internet according to http://www.builtwith.com in March 2015.

The jQuery code sample illustrates the use of chainable methods: functions constructed so they can be invoked one after another on the same object in a single statement.

You don’t have to look far for other uses of chainable methods in JavaScript. You may have recognized that the then method of the Promise API used throughout the book is chainable.

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.