Best practices for events and API calls

In this section we will look at some of the best practices for each of the tools, including how to use the API, write events, and design plug-ins using jQuery Tools functionality.

Application Programming Interface (API)

As time goes by, you will want to extend your skills with jQuery Tools you can do this by using its API, which was built to expose methods and access properties for each tool in the library. The API hides the internal values from the outside world, which is good programming practice.

To begin with, you need to create an instance of the API for that tool, such as:

//get access to the API
Var api = $("#scroller").data("scrollable")

You will notice that the argument passed to data in brackets is that of the tool name this could be changed to overlay, for example. When you have the API instance created, you can start using it, by calling its methods:

//do something upon scroll
api.onSeek(function() {
// inside callbacks the "this" variable is a reference
// to the API
console.info("current position is: " + this.getIndex())
});

You can easily see the available API methods a jQuery Tool is using with Firebug, which can act as a good source of information:

Application Programming Interface (API)

Using the API means that you are less likely to need all of jQuery's DOM methods, as most of the methods you need will be available from within the tool. This includes methods to retrieve information, as well as set values or invoke actions.

You can even chain methods onto an API instance of a tool, as the method will always return the API:

// normal API coding that programmers are accustomed to
var index = $("#example").data("tabs").click(1).getIndex();

If your selector returns multiple instances and you want to access a particular API, you can do following:

// select the correct instance with a jQuery selector
var api = $(".scrollable:eq(2)").data("scrollable");
//or with traversing methods. it is just a matter of taste
api = $(".scrollable").eq(2).data("scrollable");

jQuery Tools events

Within the API, each tool can respond to events as specific points in time where an action needs to be completed. A good example of this is Scrollable—each time you scroll through images, for example, you could fire the onSeek event. You could add your own custom responses (or listeners) each time this happens—this is particularly useful if you want to extend the default behavior of the tools.

Note

Event listeners are often referred to as callbacks—both terms are equally valid.

Before and after events

You can add your own custom functionality to any of the Tools, as they provide the before and after event methods for this purpose. These actions can equally be cancelled using the onBefore event, such as in this example, which uses the onBeforeClick callback for tabs:

$("#example").tabs(".panes > div", {
// here is a "normal" configuration variable
current: 'active',
// here is a callback function that is called before the // tab is clicked
onBeforeClick: function(event, tabIndex) {
// the "this" variable is a pointer to the API. You can do // a lot with it.
var tabPanes = this.getPanes();
/*
By returning false here the default behavior is cancelled. This time another tab cannot be clicked when "terms" are not accepted
*/
return $(":checkbox[name=terms]").is(":checked");$( ":checkbox[name=terms]").is(":checked");
}
});

Supplying events

There are three different ways of supplying event listeners in the tools:

Within the configuration

The first, and easiest, option is to include event listeners as part of your code directly:

$(".tabs").tabs({
// do your own stuff here
onClick: function() {
...
var tabPanes = this.getPanes();
}
});

A downside of using this option means that you can't specify multiple instances of the same callback in the code. For example, including two different onClick methods in the same configuration would result in an error.

Note

In the previous example, the this variable is a reference to the Tabs API.

Using jQuery's bind method

The second method follows that used within jQuery, where you can assign multiple listeners consecutively, in a chain:

// first callback
$(".tabs").bind("onClick", function() {
// "this" is a reference to the DOM element
var ulElement = this;
...
// another one
}).bind("onClick", function() {
// another one
...
});

Using this method offers greater flexibility, as it allows you to remove specific event listeners within the code, or to bind several instances of the same event listener within the same call. In the preceding example, the CSS .tabs selector is set to perform two actions when the onClick event is triggered by any of the tabs using that selector. The tools also allow you to bind the same event listener to multiple event trigger types in a single call:

// the same event listener is called before and after
// a tab is clicked
$(".tabs").bind("onBeforeClick onClick", function() {
});

It is strongly recommended that you try to familiarize yourself with this functionality in some depth, if you aren't already familiar with event binding—there is plenty of good reference material available in this area.

Supplying listeners from the API

The tools also allow you to supply one or more callbacks from within the API:

// grab the API with jQuery's data method
var api = $(".tabs").data("tabs");
// supply an event listener
api.onBeforeClick(function() {
// supply another
}).onClick(function() {
...
});

You can use the internal this variable as a reference to any of the Tools APIs, which will allow you to chain multiple event listeners together; this is more suitable for developers who are not already familiar with jQuery:

// loop through each instances
$(".tabs").each(function() {
...
// assign the onClick listener to a single instance
$(this).data("tabs").onClick(function() {
...
});
});

The event object

If you are using callbacks, it is worth noting that the Tools adhere to the current W3C standards, when passing the event object as the first argument for each callback function:

// the event object is the first argument for *all* callbacks
// in jQuery Tools
api.onClick(function(event) {
/* If you have multiple callbacks of the same type this prevents
the rest of the callbacks from being executed. */
event.stopImmediatePropagation();
...
// retrieve the value returned by the previous callback function
event.result;
event.result;
...
// whether CTRL, ALT, SHIFT, or ESC was being pressed
var alt = event.altKey,
ctrl = event.ctrlKey,
shift = event.shiftMey,
esc = event.metaKey;
...
// this is how to get the original triggering element, such
// as a handle to the scrollable navigator item that was clicked
// inside an onSeek event
var element = e.originalTarget || e.srcElement;
});

Within the scope of jQuery Tools, the preventDefault() is identical to returning false from the callback; this is considered to be the accepted practice for cancelling the default event.

Creating jQuery Tools plugins

The Tools were designed to work in tandem with jQuery, which allows you to create jQuery Tools-based plugins. Using jQuery, you can easily alter or extend the default behavior of the tools, with the added benefit of being able to reference the Tools API, and use any number of callback functions. To give you some idea, here's a simple example of a plugin that uses Google Analytics to track each click, every time a tab is selected:

// create jQuery plugin called "analytics"
$.fn.analytics = function(tracker) {
// loop through each tab and enable analytics
return this.each(function() {
// get handle to tabs API.
var api = $(this).data("tabs");
// setup onClick listener for tabs
api.onClick(function(event, index) {
tracker.trackEvent("tabs", "foo", index);
});
});
};

Tip

For those of you not familiar with writing jQuery plugins, you may like to look at the jQuery 1.4. Plugin Development Beginner's Guide, by Giulio Bai, published by Packt Publishing.

After you have included the plugin on your page, you can use the plugin in the following manner, which follows the standard format for developing the plugins:

// initialize tabs and the analytics plugin.
$("ul.tabs").tabs("div.panes > div").analytics(tracker);

jQuery Tools require that the tabs be initialized before the analytics plugin, so you cannot write:

$("ul.tabs").analytics(tracker).tabs("div.panes > div");

Using jQuery Tools plugins and effects

The design of jQuery Tools allows you to make full use of jQuery's chaining capabilities, which means you can create chain patterns, such as the following:

// initialize a few scrollables and add more features to them
$(".scroller").scrollable({circular: true}).navigator("#myNavi").autoscroll({interval: 4000});

Here, the base Scrollable call will turn any element with the .scroller class into a scrollable and the Tools' minimalist design means you are free to then extend or alter the behavior by use of additional code or plugins, such as adding the navigator or autoscroll, whilst keeping code easier to read and file sizes smaller. The net result is that you can then set up a number of scrollables on a page, which are all activated using the same single line of code, but which contain their own local configuration values (this could equally be global). This decorator philosophy forms part of the whole ethos of jQuery Tools (and indeed jQuery as a whole). Most tools come with a number of plugins that are available for download, or you can add your own custom-built ones if desired.

Effects

Coupled with the plugin architecture available with most tools, you can also design your own effects for use with some of the tools. This will allow you to change the default behavior of the tool being used, whereas plugins would be used to extend that behavior. For example, you can add an effect to control how overlay opens or closes—an example of this is the apple effect, which comes with overlay:

// use the "apple" effect for the overlays
$("a[rel]").overlay({effect: 'apple'});

The use of additional effects means that you can hive off code into separate files, which makes the base overlay code smaller and more organized. You can then take this a step further by creating more effects that can be referenced from separate files, and dropped into your code as necessary. You could also set a specific effect to be used as your default effect, from within a global configuration; this reduces the need to specify in each instance it is used in your code. You can also achieve the same effect with configuration values—if you have a number of values that are set as part within an effect, you can then set these to apply by default at a global level, for every instance where this effect is used. For example, you may have an explosionSpeed value set in your effect—the following would turn it into a global configuration variable:

$.tools.overlay.conf.explosionSpeed = 500;

It is worth having a look at http://gsgd.co.uk/sandbox/jquery/easing/, the home of the jQuery Easing plugin; there are a number of effects there, that can be adapted for use within jQuery Tools.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset