views:

75

answers:

3

To make my question more specific, I read the documentation on .each() for jQuery, but I am a little more confused. I have this code:

$.fn.imgAreaSelect = function (options) {
options = options || {};

this.each(function () {
    if ($(this).data('imgAreaSelect')) {
        if (options.remove) {
            $(this).data('imgAreaSelect').remove();
            $(this).removeData('imgAreaSelect');
        }
        else
            $(this).data('imgAreaSelect').setOptions(options);
    }
    else if (!options.remove) {
        if (options.enable === undefined && options.disable === undefined)
            options.enable = true;

        $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
    }
});

if (options.instance)
    return $(this).data('imgAreaSelect');

return this;

};

Now what I don't get about this is that why does the each function not have an index or an element? This snippet of code is from a jQuery plugin that I was trying to read over. I also don't quite understand the $.fn. at the top, i know it stands for prototype, but what's exactly going on here?

+2  A: 

It doesn't need an index, since this provides the context. As noted by the docs, "The value can also be accessed through the this keyword." This is accomplished by using call. Something like:

userFunction.call(valueOfElement, indexInArray, valueOfElement);

$.fn.imgAreaSelect = function (options) means the function is being added to the prototype. This allows it to be used with any instance of the jQuery object.

Matthew Flaschen
A: 

$.each(fn) calls fn for each element contained in the current context. Each time it calls fn, it passes the "current" element as this.

So in the following example:

$("div").each(function() {
    alert(this.className);
});

Will pop up one alert for each <div> in the DOM, and display the class name of each.

Dean Harding
+4  A: 

The each function can take a function accepting an index as a parameter, but it's optional.

For simplicity's sake, .each was implemented to have this refer to the current element.

However, .each can accept an index as a parameter to it's callback.

There's an example of that usage in the jQuery API

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
  });

Reference - http://api.jquery.com/each/

Jamie Wong