JQuery Cookbook

Page 292

Accessing this new plugin is as simple as calling jQuery like you normally would and utilizing your new method name: jQuery('p').goShop();

Writing a custom jQuery function Functions are attached to the main jQuery object. Functions are designed to be called outside of a jQuery selection: jQuery.checkout = function() { jQuery('body').append('<h1>Checkout Successful</h1>'); };

This new function can be manipulated and called normally: jQuery.checkout();

Discussion Attaching new methods and functions to the main jQuery object are a powerful feature of jQuery. Many of the core methods are built into the library using this same technique. By leveraging this existing foundation in jQuery, users of jQuery and users of your plugin have a fast and concise way to add new functionality, extend existing functionality, and mold the jQuery code into whatever form suits them best. This flexibility is a key feature and enables jQuery and its plugins to be used by a wider audience. The choice to extend jQuery via a new method or a function mainly depends on the needs of the developer. In general, focusing on extending jQuery via adding a new method is best because this allows that new method to be chained along with other methods, and it allows the code in the method to take advantage of jQuery’s selector engine.

12.4 Passing Options into Your Plugin Problem Your first plugin adds a method to jQuery. However, there are a few options that would be helpful to others if they were exposed properly. What is the best method of passing options into a custom method?

Solution Options are best passed into your custom plugin method via an options object. Using a single options object to pass in parameters promotes cleaner code, is easier to work with, and provides flexibility down the road. When allowing options to be utilized in your plugin, it’s wise to provide sensible defaults. After providing sensible default options, it’s also important that your plugin

268 | Chapter 12: jQuery Plugins


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.