ENTERPRISE

jQuery 1.3 : Developing plugins - Adding jQuery Object Methods

10/12/2010 3:15:12 PM
Most of jQuery's built-in functionality is provided through its object methods, and this is where plugins shine as well. Whenever we would write a function that acts on part of the DOM, it is probably appropriate instead to create an object method.

We have seen that adding global functions requires extending the jQuery object with new methods. Adding instance methods is similar, but we instead extend the object: jQuery.fn

jQuery.fn.myMethod = function() {
alert('Nothing happens.');
}

The jQuery.fn object is an alias to jQuery.prototype, provided for conciseness.


We can then call this new method from our code after using any selector expression:

$('div').myMethod();

Our alert is displayed when we invoke the method. We might as well have written a global function, though, as we haven't used the matched DOM nodes in any way. A reasonable method implementation acts on its context.

Object Method context

Within any plugin method, the keyword this is set to the current jQuery object. Therefore, we can call any built-in jQuery method on this, or extract its DOM nodes and work on them:

jQuery.fn.showAlert = function() {
alert('You selected ' + this.length + ' elements.');
}

To examine what we can do with object context, we'll write a small plugin to manipulate the classes on the matched elements. Our new method will take two class names, and swap which class is applied to each element with every invocation.

jQuery.fn.swapClass = function(class1, class2) {
if (this.hasClass(class1)) {
this.removeClass(class1).addClass(class2);
}
else if (this.hasClass(class2)) {
this.removeClass(class2).addClass(class1);
}
};

First, we test for the presence of class1 on the matched element and substitute class2 if it is found. Otherwise, we test for class2 and switch in class1 if necessary. If neither class is currently present, we do nothing.

To test out our method, we need some HTML to play with:

<ul>
<li>Lorem ipsum dolor sit amet</li>
<li class="this">Consectetur adipisicing elit</li>
<li>Sed do eiusmod tempor incididunt ut labore</li>
<li class="that">Magna aliqua</li>
<li class="this">Ut enim ad minim veniam</li>
<li>Quis nostrud exercitation ullamco</li>
<li>Laboris nisi ut aliquip ex ea commodo</li>
<li class="that">Duis aute irure dolor</li>
</ul>
<input type="button" value="Swap classes" id="swap" />

The class this is styled as bold text, and the class that is styled as italic text:

Now, we can invoke our method whenever the button is clicked:

$(document).ready(function() {
$('#swap').click(function() {
$('li').swapClass('this', 'that');
return false;
});
});

But something is wrong. When we click the button, every row gets the that class applied:

We need to remember that a jQuery selector expression can always match zero, one, or multiple elements. We must allow for any of these scenarios when designing a plugin method. In this case, we are calling .hasClass(), which only examines the first matched element. Instead, we need to check each element independently and act on it.

The easiest way to guarantee proper behavior regardless of the number of matched elements is to always call .each() on the method context; this enforces implicit iteration, which is important for maintaining consistency between plugin and built-in methods. Within the .each() call, this refers to each DOM element in turn, so we can adjust our code to separately test for and apply classes to each matched element.

jQuery.fn.swapClass = function(class1, class2) {
this.each(function() {
var $element = jQuery(this);
if ($element.hasClass(class1)) {
$element.removeClass(class1).addClass(class2);
}
else if ($element.hasClass(class2)) {
$element.removeClass(class2).addClass(class1);
}
});
};

Caution! The keyword this refers to a jQuery object within the object method's body, but refers to a DOM element within the .each() invocation.


Now when we click the button, the classes are switched without affecting the elements that have neither class applied:

Method chaining

In addition to implicit iteration, jQuery users should be able to rely on chaining behavior. This means that we need to return a jQuery object from all plugin methods, unless the method is clearly intended to retrieve a different piece of information. The returned jQuery object is usually just the one provided as this. If we use .each() this, we can just return its result: to iterate over

jQuery.fn.swapClass = function(class1, class2) {
return this.each(function() {
var $element = jQuery(this);
if ($element.hasClass(class1)) {
$element.removeClass(class1).addClass(class2);
}
else if ($element.hasClass(class2)) {
$element.removeClass(class2).addClass(class1);
}
});
};

Previously, when we called .swapClass() we had to start a new statement to do anything else with the elements. With the return statement in place, though, we can freely chain our plugin method with built-in methods:

$(document).ready(function() {
$('#swap').click(function() {
$('li')
.swapClass('this', 'that')
.css('text-decoration', 'underline');
return false;
});
});

Other  
 
Video tutorials
- How To Install Windows 8 On VMware Workstation 9

- How To Install Windows 8

- How To Install Windows Server 2012

- How To Disable Windows 8 Metro UI

- How To Change Account Picture In Windows 8

- How To Unlock Administrator Account in Windows 8

- How To Restart, Log Off And Shutdown Windows 8

- How To Login To Skype Using A Microsoft Account

- How To Enable Aero Glass Effect In Windows 8

- How To Disable Windows Update in Windows 8

- How To Disable Windows 8 Metro UI

- How To Add Widgets To Windows 8 Lock Screen
programming4us programming4us
Top 10
Free Mobile And Desktop Apps For Accessing Restricted Websites
MASERATI QUATTROPORTE; DIESEL : Lure of Italian limos
TOYOTA CAMRY 2; 2.5 : Camry now more comely
KIA SORENTO 2.2CRDi : Fuel-sipping slugger
How To Setup, Password Protect & Encrypt Wireless Internet Connection
Emulate And Run iPad Apps On Windows, Mac OS X & Linux With iPadian
Backup & Restore Game Progress From Any Game With SaveGameProgress
Generate A Facebook Timeline Cover Using A Free App
New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th