1. Trang chủ
  2. » Công Nghệ Thông Tin

JQuery: Novice to Ninja- P28 pot

15 201 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 15
Dung lượng 416,85 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

We all knew what it did, but now we know what it’s called: Two = signs together, ==, is known as the equality operator, and establishes a Boolean value.. In our example, the variable cw

Trang 1

Licensed to JamesCarlson@aol.com

When we “add” a string and a number using the + operator, JavaScript assumes

we’re trying to concatenate the two, so it creates a new string It would appear to

change the number’s variable type to string When we use the multiplication oper­

ator (*) though, JavaScript assumes that we want to treat the two variables as num­

bers

The variable itself remains the same throughout, it’s just treated differently We can

always explicitly tell JavaScript how we intend to treat a variable, but if we don’t,

we need to understand just what JavaScript is doing for us Here’s another example:

Equality Operators

The equal sign (=) and its related operators can also provide a trap for young players

And where it was once just a little odd, it became even more so in JavaScript 1.3

The first trick is that the equal sign has a different meaning than what you remember

from your school mathematics classes:

A single equal sign is an assignment operator, and is used to assign values to vari­

ables We all knew what it did, but now we know what it’s called:

Two = signs together, ==, is known as the equality operator, and establishes a

Boolean value In our example, the variable cwill have a value of true, as JavaScript

compares the values before and after the equality operator, and considers them to

be equal Using the equality operator, JavaScript pays no heed to the variable’s type,

and attempts to coerce the values to assess them

Switch out the first equal sign for an exclamation mark, and you have yourself an

inequality operator (!=) This operator will return false if the variables are equal,

or true if they aren’t:

Trang 2

Licensed to JamesCarlson@aol.com

The variable d will now have a value of false, since a and b are equal It may be a

little complex, but at least it’s consistent

In JavaScript 1.3, the situation became less simple still, with the introduction of

one further operator: the strict equality operator, shown as ===

The strict equality operator differs from the equality operator, in that it pays strict

attention to type as well as value when it assigns its Boolean In the above case, d

is set to false: while a and b both have a value of 2, they have different types

And as you might have guessed, where the inequality operator was paired with the

equality operator, the strict equality operator has a corresponding strict inequality

operator:

In this case the variable fwill return true, as we know the two compared variables are of different types, though similar values

Suffice it to say that some equal signs are more equal then others!

Truthiness and Falsiness

JavaScript’s Boolean type has two possible values—true and false:

But we know that JavaScript likes to be trickier than this In reality, there are a

multitude of ways that variables can evaluate to true or false These values are

referred to as being truthy or falsy So when we write if(variable) { … }, variable need not be a Boolean value: the code between the brackets will run if variable

contains the number 5, or the string "Hello World!", or even an empty array Any

Trang 3

Licensed to JamesCarlson@aol.com

value that acts as though it were the Boolean value true in this type of context is

called truthy, and any value that acts like false is called falsy

JavaScript treats all these values as truthy:

■ true

■ 1 (because it’s a non-zero number)

■ "0" (because it’s a non-empty string)

■ "false" (because it’s a non-empty string)

■ function() {} (any function)

■ {} (any object)

■ [] (any array)

And these values are falsy:

■ false

■ 0 (the number zero)

■ "" (an empty string)

■ null

■ undefined

■ NaN (a special number value meaning Not a Number)

These values can be combined with the logical NOT operator to great effect A single

exclamation mark is used:

The logical NOT operator returns true if the value of the variable is false and,

conversely, it will return falseif the value is true In the example above, bis truthy

and so !b returns false, and a is falsy so !a returns true—so the code in the else

if block would execute

Trang 4

Licensed to JamesCarlson@aol.com

It’s important to remember that while a value may be == true, it may only be truthy,

and not strictly true:

If you have the option, always elect to use the Boolean values of true and false

If there’s one thing that’s undoubtedly true, it’s that hunting down a truthy or falsy

logic error is truly painstaking!

Trang 5

Licensed to JamesCarlson@aol.com

Trang 6

Licensed to JamesCarlson@aol.com

There are a few jQuery properties and actions that, although applying to any jQuery

selection, are particularly useful for plugin development The reason they’re hidden

away in this appendix is that they’re uncommonly used Despite this, they’re quite

powerful, and you should familiarize yourself with them if you intend to spend

time developing plugins

Selector and Context

The first ones we’ll look at are the selector and context properties These work

together to show you what jQuery thinks it’s working on

The selector property returns a string value of the current jQuery selector string:

so the command $('p:first').selector will return the string "p:first" This is

useful in your plugins if you need to know what the user originally selected

You might think that the optional second parameter to the jQuery selector, which

is called context, is what you’d obtain with the context property—but it’s a bit

trickier than that In fact, if you supply contextas a string, it’s converted internally

to a regular jQuery statement, which will actually affect the selector property:

In the above example, the selectorresolves to "#content p:first"and the context resolves to Document(the context that all your selectors will default to) The context property is only modified if you supply an actual DOM node to it:

In this case, the selector will be reported as "p:first", and the context will be

the DOM element itself (for this example, it’s the <div id="content"> element)

Trang 7

Licensed to JamesCarlson@aol.com

Specifying the DOM node provides no guarantee that your queries will run faster;

internally jQuery’s selector engine will only search inside the context you specify

anyway, even though the context property will be reported as Document

The jQuery Stack

To make our plugins play nicely with jQuery, we’ve learned that we should return

each jQuery element from our code, so that commands can continue to be chained

after our plugin Generally, we just modify elements in the selection before we pass

them back, but sometimes we want to alter the items that are returned—perhaps

remove some elements, or add some new ones The best way to accomplish this is

via the pushStack action This is a convenient way to create a jQuery selection for

inclusion in the chain

By way of example, we’ll set up a small plugin that retrieves the elements that sur­

round the selected element The use case might be to highlight the next and previous

items in a list of elements Our plugin will also wrap around if the selected item is

the first or last in the list:

The plugin retrieves the previous and next elements, and combines them into one

selection with the addaction This new collection is returned via pushStack, which

accepts the collection, a name for it, and a name for the selector string The two

name parameters will be readable by the selectorproperty we looked at above To

use this plugin, we might apply it to an unordered list called categories, like so:

Trang 8

Licensed to JamesCarlson@aol.com

This will select the two elements that surround the first list item, then color them

red Because we’ve used pushStack, the jQuery chain remains intact; we can then

use the endcommand to move back to the original selection (the first list item), and

color it blue You can use pushStack anytime you want to manipulate the chain

like this

The last trick we’ll look at in regard to the jQuery internal chain is the ability to

access other steps in the chain As you might remember, the end action takes you

back up one level to the last command that modified the jQuery selection If you

look into the jQuery core, you’ll see that end is implemented using the prevObject property Inside your plugin you can gain access to the previous jQuery object by

using this.prevObject If the previous object has a previous object, you can access

this too!

Minification

You know there are two versions of jQuery, jQuery UI, and many jQuery plugins:

an uncompressed version and a minified version Why is this so?

Regardless of which one you choose, when you add them to your page you gain

access to all the features of jQuery (or the plugin in question) The difference is, of

course, that the file size of the “.min” version is markedly smaller With jQuery 1.3.2

coming in at around 118KB and the minified version at 55.9KB, you save over half

the file size in bandwidth

And if the file is half as big, it’s delivered twice as fast Faster downloads mean

faster pageloads, so you may be wondering how to enjoy the benefit of minified

files with your own script files, and—more importantly—your plugins

There are a number of utilities you can use to compress your files, so we’ll go over

a few of the more commonly used ones

Trang 9

Licensed to JamesCarlson@aol.com

Douglas Crockford’s JSMin1 was first released in December of 2003, and currently

comes in both the original executable version (along with the C source code), as

well as a host of other language options: C#, Java, JavaScript, Perl, PHP, Python,

OCaml, and Ruby

Of a similar pedigree, but slightly more accessible to use, is Dean Edwards’ Packer.2

It’s primarily accessed via a web page interface, but it also has NET, Perl, and PHP

applications available for download

Both solutions work by eliminating whitespace—line breaks and extraneous

spaces—and by shortening variable and function names The code becomes obfus­

cated by human standards, but the browser’s JavaScript engine has no trouble inter­

preting the code output So, for example, this human-readable code:

… would be shortened to this:

➥"-6px",opacity :0,paddingBottom:0,paddingTop:0,queue:false}

The second statement has the whitespace removed, and you can already see that

it’s taking up less space to achieve the same results You can also see how it’s become

more difficult to read Multiply this effect by the 4,377 lines in the jQuery source,

and you can imagine how difficult it would be to make any sense of it And that’s

without altering any names

Trang 10

Licensed to JamesCarlson@aol.com

Of these two methods, Packer is arguably the more extensive, not only removing

whitespace but also converting names to base 62 Its compressed footprint can

therefore be smaller, yet this mightn’t necessarily result in the fastest solution, as

it means the minified code must be “unpacked” when delivered to the browser

Edwards’ most recent modifications have seen some astounding increases in unpack­

ing speeds, but this overhead should be considered when adopting a final solution

Two other popular options for minifying your JavaScript are Yahoo’s YUI Com­

pressor3 and Google’s Closure Compiler.4

The teams behind all four methods—well, three, as Crockford is fairly much sorted

with JSMin—are continually refining their solutions, and are responsive to industry

and community feedback

Trang 11

Licensed to JamesCarlson@aol.com

Trang 12

Licensed to JamesCarlson@aol.com

Index

Symbols

A

Trang 13

Licensed to JamesCarlson@aol.com

394

API (Application Programming Inter­

Asynchronous JavaScript and XML (see

Trang 14

Licensed to JamesCarlson@aol.com

395

axis option (draggable interaction help­

B

C

Trang 15

Licensed to JamesCarlson@aol.com

396

D

Ngày đăng: 03/07/2014, 07:20