Book Image

jQuery Design Patterns

By : Thodoris Greasidis
Book Image

jQuery Design Patterns

By: Thodoris Greasidis

Overview of this book

jQuery is a feature-rich JavaScript library that makes HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a variety of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. jQuery solves the problems of DOM manipulation, event detection, AJAX calls, element selection and document queries, element attribute and data management, as well as object management utilities. This book addresses these problems and shows you how to make the best of jQuery through the various design patterns available. The book starts off with a refresher to jQuery and will then take you through the different design patterns such as facade, observer, publisher/subscriber, and so on. We will also go into client-side templating techniques and libraries, as well as some plugin development patterns. Finally, we will look into some best practices that you can use to make the best of jQuery.
Table of Contents (18 chapters)
jQuery Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Preface

Since its introduction in 2006, the jQuery library has made DOM traversals and manipulations much easier. This has resulted in the appearance of Web pages with increasingly complex user interactions, thus contributing to the maturing of Web as a platform capable of supporting large application implementations.

This book presents a series of best practices that make the implementation of Web applications more efficient. Moreover, we will analyze the most important Design Patterns that Computer Science has to offer, which can be applied to Web development. In this way, we will learn how to utilize techniques that are thoroughly used and tested in other fields of programming, which were initially created as generic methods to model solutions of complex problems.

In jQuery Design Patterns, we will analyze how various Design Patterns are utilized in the implementation of jQuery and how they can be used to improve the organization of our implementations. By adopting the Design Patterns demonstrated in this book, you will be able to create better organized implementations that resolve large problem categories faster. Moreover, when used by a developer team, they can improve the communication between them and lead to homogenous implementation, where every part of the code is easily understood by others.

What this book covers

Chapter 1, A Refresher on jQuery and the Composite Pattern, will teach the reader how to write the code using the Composite Pattern and method chaining (Fluent Interface) by analyzing how they are used for the implementation of jQuery itself. It also demonstrates the Iterator Pattern that nicely pairs with the Composite Collection objects that jQuery returns.

Chapter 2, The Observer Pattern, will teach you how to respond to user actions using the Observer Pattern. It also demonstrates how to use Event Delegation as a way to reduce the memory consumption and complexity of the code that handles dynamically injected page elements. Finally, it will teach you how to emit and listen for Custom Events in order to achieve greater flexibility and code decoupling.

Chapter 3, The Publish/Subscribe Pattern, will teach you how to utilize the Pub/Sub Pattern to create a central point to emit and receive application-level events, as a way to decouple your code and business logic from the HTML that is used for presentation.

Chapter 4, Divide and Conquer with the Module Pattern, demonstrates and compares some of the most commonly used Module Patterns in the industry. It will teach you how to structure your application in small independent Modules using Namespacing, leading to expandable implementations that follow the Separation of Concerns principle.

Chapter 5, The Facade Pattern, will teach you how to use the Facade Pattern to wrap complex APIs into simpler ones that are a better match for the needs of your application. It also demonstrates how to change parts of your application, while keeping the same module-level APIs and avoid affecting the rest of your implementation.

Chapter 6, The Builder and Factory Patterns, explains the concepts of and the differences between the Builder and Factory Patterns. It will teach you how and when to use each of them, in order to improve the clarity of your code by abstracting the generation of complex results into separate dedicated methods.

Chapter 7, Asynchronous Control Flow Patterns, will explain how jQuery's Deferred and Promise APIs work and compare them with the classical Callbacks Pattern. You will learn how to use Promises to control the the execution of asynchronous procedures to run either in an order or parallel to each other.

Chapter 8, Mock Object Pattern, teaches you how to create and use Mock Objects and Services as a way to ease the development of your application and get a sense of its functionality, long before all its parts are completed.

Chapter 9, Client-side Templating, demonstrates how to use the Underscore.js and Handlebars.js templating libraries as a better and faster way to create complex HTML structures with JavaScript. Through this chapter, you will get an overview of their conventions, evaluate their features, and find the one that best matches your taste.

Chapter 10, Plugin and Widget Development Patterns, introduces the basic concepts and conventions of jQuery Plugin development and analyzes the most commonly used design patterns, so that you will be able to identify and use the best match for any use case.

Chapter 11, Optimization Patterns, guides you with the best tips to create a highly efficient and robust implementation. You will be able to use this chapter as a checklist of best practices that improve the performance and lower the memory consumption of your applications, before moving them to a production environment.

What you need for this book

In order to run the examples in this book, you will need to have a web server installed on your system to serve the code files. For example, you can use Apache or IIS or NGINX. In order to make the installation process of Apache easier, you can use more complete development environment solutions, such as XAMPP or WAMP Server.

In terms of technical proficiency, this book assumes that you already have some experience of working with jQuery, HTML, CSS, and JSON. All the code samples in the book use jQuery v2.2.0 and some of the chapters also discuss the respective implementation in jQuery v1.12.0, which can be used in case support for older browsers is needed.

Who this book is for

This book targets existing jQuery developers or new developers who want to take their skills and understanding to an advanced level. It is a detailed introduction to how the various industry standard patterns can be applied to jQuery applications, and along with a set of the best practices, it can help large teams collaborate and create well organized and extendable implementations.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "In the preceding CSS code, we first defined some basic styles for the box, boxsizer, and clear CSS classes."

A block of code is set as follows:

$.each([3, 5, 7], function(index){
    console.log(this + 1 + '!');
});

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

$('#categoriesSelector').change(function() { 
    var $selector = $(this); 
    var message = { categoryID: $selector.val() }; 
    broker.trigger('dashboardCategorySelect', [message]); 
});

We are following Google's JavaScript Style Guide, except from using four spaces for indentation, in order to improve the readability of the code in the book. In short, we are placing curly brackets on top and use single quotes for string literals.

Note

For more information on Google's JavaScript Style Guide you can visit the following URL: https://google.github.io/styleguide/javascriptguide.xml

Any command-line input or output is written as follows:

npm install jquery

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The jQuery Object returned is an Array-like object that acts as a wrapper object and carries the collection of the retrieved elements."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.