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

The Object Literal Pattern


The Object Literal Pattern is probably the simplest way to wrap all the related parts of an implementation under an umbrella object that works as a Module. The name of this pattern accurately describes the way it is used. The developer just needs to declare a variable and assign an object with all the related parts that need to be encapsulated into this Module.

Let's see how we can create a Module that provides unique integers to a page, in a similar way how jquery.guid does it:

var simpleguid = { 
  guid: 1, 
  init: function() { 
    this.guid = 1; 
  }, 
  increaseCounter: function() { 
    this.guid++; 
    // or simpleguid.guid++;
  }, 
  getNext: function() { 
    var nextGuid = this.guid; 
    this.increaseCounter(); 
    return nextGuid; 
  } 
};

As seen above, a simple rule that you can follow in order to adopt this pattern is to define all the variables and functions that each implementation needs as properties of an object. Our code is reusable and does...