Web Development with jQuery®

(Elliott) #1

(^368) ❘ CHAPTER 14 SELECTABLE
In addition to styling the folder icon, the following style is applied to the name of the fi le or folder:
div.finderSelected div.finderDirectoryName span,
div.finderDirectoryDrop div.finderDirectoryName span {
background: rgb(56, 117, 215);
border-radius: 8px;
color: white;
padding: 1px 7px;
}
Then, for each fi le object that selectFile() is called on, you see if that fi le object is already added to
the finder.selectedFiles array. This array keeps track of every fi le that is selected at a given time by
storing a reference to it. jQuery’s inArray() method is designed to work like JavaScript’s indexOf()
method. The indexOf() is used to determine if a string contains another string. If the string is found,
then indexOf() returns the offset position of the fi rst occurrence of that string, where counting from
zero, the fi rst character in the string you’re searching is number zero. If indexOf() returns an inte-
ger zero or greater, then the string is found within the second string and that number can be used
to identify where in that string the second string exists. If indexOf() returns -1, then the string is
not found. jQuery’s inArray() works the same way it applies the same logic using arrays instead of
strings. If a value is found within the array, the offset position of that value is returned. The array
is also numbered starting from zero, so the fi rst item within the array is number zero and each item
is numbered from there. inArray() returns -1 if the value does not exist within the array, otherwise
inArray()returns a number zero or greater.
selectFile : function()
{
this.addClass('finderSelected');
this.each(
function()
{
if ($.inArray($(this), finder.selectedFiles) == -1)
{
finder.selectedFiles.push($(this));
}
}
);
return this;
},
To unselect fi les, the fi rst thing that you do is to remove the class name fi nderSelected using the
removeClass() method. Then the elements passed to unselectFile(), which are made available in
the this keyword, are assigned to a new variable called files. This is done to make the elements
available within the anonymous function passed to the grep() method. You then verify that finder.
selectedFiles is an array and contains one or more items. The grep() method is used to fi lter the
finder.selectedFiles array. The anonymous function provided to grep() is executed once for every
item in the array. If the anonymous function provided to grep() returns true, then the item remains
in the array. If the anonymous function returns false, however, then the item is removed from the
array. In the context of this example, if the fi le is among the fi les to be unselected, then fi le or fi les
are removed from the finder.selectedFiles array via grep().
http://www.it-ebooks.info

Free download pdf