Tải bản đầy đủ (.pdf) (430 trang)

pro javascript with mootools

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.12 MB, 430 trang )

BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Pro JavaScript with MooTools
Pro JavaScript with MooTools is unlike any other JavaScript book on the mar-
ket today. While similar books focus on either JavaScript as a language of the
browser or how to use JavaScript frameworks, Pro JavaScript with MooTools
fills the gap between these topics and moves beyond—exploring the advanced
features of JavaScript and how the MooTools framework uses these features to
further improve the language itself.
The book itself takes a unique three-pronged approach. It first walks you
through the advanced features of JavaScript and the MooTools framework,
including native augmentation and type creation, a comprehensive discussion
of JavaScript functions, object-oriented programming with native JavaScript
and MooTools Classes, and the MooTools Class internals. You’ll then learn
all about JavaScript in the DOM: the Elements Class and its internals, the
MooTools Event system, Selector engines and MooTools Slick, Ajax and the
Request Object, and Animation and the Fx classes.
The final section really sets the book apart from all others, as it discusses
JavaScript outside the browser. You’ll take an in-depth look at CommonJS
and MooTools, using MooTools outside the browser using Meso, and creating
CommonJS web applications via the MooTools Deck framework.
Mark Joseph Obcena
US $44.99
Shelve in:
Web Development / JavaScript
User level:
Intermediate–Advanced
THE APRESS ROADMAP
Pro
JavaScript Design Patterns
Pro JavaScript


with MooTools
MooTools
Essentials
Practical Prototype
and script.aculo.us
Beginning JavaScript
with DOM Scripting
www.apress.com
SOURCE CODE ONLINE
Companion eBook

Obcena
JavaScript with MooTools
Companion
eBook Available
Pro
THE EXPERT’S VOICE
®
IN WEB DEVELOPMENT
Pro
JavaScript
with MooTools
Learning Advanced JavaScript Programming
Mark Joseph Obcena
Foreword by Valerio Proietti, MooTools Founder and Lead Developer
Extending the Power of JavaScript Beyond
the Browser by Using MooTools
Written for
MooTools 1.3
www.it-ebooks.info












www.it-ebooks.info

i

Pro JavaScript with
MooTools
Learning Advanced
JavaScript Programming













■ ■ ■
Mark Joseph Obcena

www.it-ebooks.info

ii
Pro JavaScript with MooTools: Learning Advanced JavaScript Programming
Copyright © 2010 by Mark Joseph A. Obcena
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-3054-0
ISBN-13 (electronic): 978-1-4302-3055-7
Printed and bound in the United States of America (POD)
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.
President and Publisher: Paul Manning
Lead Editors: Frank Pohlmann and Ben Renow-Clarke
Technical Reviewer: Simo Kinnunen
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick,
Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank
Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Mary Tobin
Copy Editor: Sharon Terdeman

Compositor: MacPS, LLC
Indexer: Julie Grady
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring
Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
, or visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com.

www.it-ebooks.info

iii



To the one who owns my heart.
www.it-ebooks.info

iv
Contents at a Glance

■Contents v

■Foreword xiv
■About the Author xv
■About the Technical Reviewer xvi
■Acknowledgments xvii
■Preface xviii
Part I: Exploring JavaScript and MooTools 1
■Chapter 1: JavaScript and MooTools 3
■Chapter 2: Functions 11
■Chapter 3: Objects 47
■Chapter 4: Classes 71
■Chapter 5: Classes: The Extras 99
■Chapter 6: Types 127
Part II: Conquering the Client Side 171
■Chapter 7: JavaScript in a Window 173
■Chapter 8: Elements 187
■Chapter 9: Selector Engines 245
■Chapter 10: Events 261
■Chapter 11: Request 307
■Chapter 12: Animation 339
Part III: Breaking from the Browser 359
■Chapter 13: JavaScript without Limits 361
■Chapter 14: MooTools on Deck 371
■Appendix: Resources 387
■Index 389
www.it-ebooks.info

v
Contents



Contents at a Glance iv
■Foreword xiv
■About the Author xv
■About the Technical Reviewer xvi
■Acknowledgments xvii
■Preface xviii

Part I: Exploring JavaScript and MooTools 1
■Chapter 1: JavaScript and MooTools 3
JavaScript 3
MooTools 4
The Language Extension 5
Your Toolkit 5
JavaScript Interpreter 6
JavaScript Console 6
MooTools Core and the Snippet Runner 8
Code Editor and JSLint 9
The Wrap Up 10
■Chapter 2: Functions 11
The Function 11
One Function, Multiple Forms 12
Function Declaration 12
Function Expression 14
Named Function Expression 15
www.it-ebooks.info
■ CONTENTS
vi
Single-Execution Function 17
Function Object 19
Arguments 20

Return Values 24
Function Internals 25
Executable Code and Execution Contexts 25
Variables and Variable Instantiation 27
Scoping and the Scope Chain 29
Closures 31
The “this” Keyword 33
Advanced Function Techniques 36
Limiting Scope 36
Currying 38
Decoration 39
Combination 41
MooTools and Functions 42
Function Binding 43
Extending Functions with Methods 44
The Wrap Up 46
■Chapter 3: Objects 47
JavaScript is Prototypal(-ish) 47
A Language of Objects 48
The Building Blocks of Objects 50
Constructor Functions 50
Prototypes 53
Inheritance 56
The Prototype Chain 61
Deliberate Chains 63
Simplified Prototypal Programming 65
www.it-ebooks.info
■ CONTENTS
vii
The Wrap Up 68

■Chapter 4: Classes 71
From Prototypes to Classes 71
The MooTools Class System 73
Constructors and Initializers 75
Rethinking Members 77
Rethinking Methods 78
Rethinking Properties 80
Inheritance 83
Overridden Methods 86
Inside this.parent() 90
Mixins 91
The Wrap Up 96
■Chapter 5: Classes: The Extras 99
Mutators 99
Implementing Your Own Mutators 101
Mutator Gotchas 104
The Built-in Mixins 106
The Chain Mixin 106
The Events Mixin 109
The Options Mixin 112
Static Members 114
Encapsulation and Visibility 118
Private Methods 120
Protected Methods 121
MooTools and Classes 125
The Wrap-Up 126
■Chapter 6: Types 127
Values and Type Systems 127
www.it-ebooks.info
■ CONTENTS

viii
An Alternative Type System 129
Native Types and Values 131
Null and Undefined 131
Primitive Types 132
Composite Types 135
Type Casting 143
Casting Using Constructors 144
Casting Using Native Functions and Idioms 145
The MooTools Type System 147
The Type Constructor and Function Subclassing 147
Instance Checking 148
Type Detection 151
Working with Type Objects 152
Implementing New Members 153
Aliases and Mirroring 155
The extend Method and Generics 158
Creating New Types 160
A Table Type 160
The Table Constructor 162
Setter, Getter, and Removal 163
Membership Methods 164
Keys, Values and Traversals 165
Our Final Type 167
The Wrap-Up 168
Part II: Conquering the Client Side 171
■Chapter 7: JavaScript in a Window 173
A Language for Every Computer 173
Life Cycle of a Page 174
Pause, Script 175

www.it-ebooks.info
■ CONTENTS
ix
The Scripted Browser 176
The Document Object Model 177
The Browser Object Model 178
Frameworks, Libraries, and Toolkits 182
MooTools and the Browser 183
Fixing Browsers with MooTools 183
Browser Detection 185
Feature Detection 185
The Wrap-Up 186
■Chapter 8: Elements 187
Families and Trees 187
Is My DOM Ready Yet? 191
DOM Scripting with MooTools 198
Selecting Elements 198
An Elemental Segue 215
Moving Elements Around 218
Modifying Element Objects 227
Creating Elements 231
Destroying Elements 235
The Element Type 235
Revisiting document.id 236
Extending Element 238
The Elements Type 239
The Universal Modificators 239
Element Storage 241
The Wrap Up 242
■Chapter 9: Selector Engines 245

What Node? 245
Selecting in Style 248
www.it-ebooks.info
■ CONTENTS
x
Selector Engines 249
A Whirlwind Tour of CSS Selector Notation . 249
Slick: the MooTools Selector Engine 252
Selecting Elements with Slick . 252
Combinator Prefixes 253
Reverse Combinators 254
Pseudo-Selector Functions 255
Inside Slick . 256
The Slick Parser Engine 256
The Slick Selection Engine 258
The Wrap-Up . 259
■Chapter 10: Events . 261
A Loopy World 261
The Event Loop 263
Event-Based Programming 264
The Event Models 265
The Internet Explorer Model . 265
The DOM Level 2 Model 273
The MooTools Event System . 288
Attaching Event Handlers 288
Preventing Default Action . 291
Stopping Event Propagation 292
Stopping Events All Together . 293
Detaching Event Handlers 294
Dispatching Events 295

Event System Internals 296
The Event Type 296
Two Layers 299
The Event Table 299
Event Handler Wrapping 300











www.it-ebooks.info
■ CONTENTS
xi
Event Handler Detachment and Dispatch 304

Custom Events 305
The Wrap-Up 306
■Chapter 11: Request 307
Requests and Responses 307
The XMLHttpRequest Object 309
Going Async 314
The MooTools Request Class 319
Creating New Requests 320
Adding Request Headers 321

Sending Data 322
Attaching Event Handlers 323
Timeouts 328
Event Handler Declarations 330
Sending the Request 331
Request Sending Modes 332
Our Final Code 333
Subclassing Request 335
Request Internals 335
Success Overriding 336
The Wrap-Up 337
■Chapter 12: Animation 339
Getting Animated 339
Being Stylish 340
CSS Styles 341
Explicit, Implicit, and Computed 342
Revisiting Style Methods 342
Time for Some Action 343
Timers 343
www.it-ebooks.info
■ CONTENTS
xii
Timer Execution 345

A Basic JavaScript Animation 346
MooTools Fx Classes 349
Animation Objects 349
Tween and Morph 351
Fx Methods and Events 353
Fx Internals 354

The Fx Base Class 354
CSS Animation 356
The Wrap-Up 357
Part III: Breaking from the Browser 359
■Chapter 13: JavaScript without Limits 361
Breaking out of the Browser 361
CommonJS 362
Common Modules 363
Export and Require 363
Module Paths 365
MooTools and CommonJS 367
Meso: MooTools in the Middle 368
The Wrap-Up 369
■Chapter 14: MooTools on Deck 371
Revisiting Request and Response 371
JavaScript on the Server 373
JSGI 373
JSGI and CommonJS Engines 376
A Common Deck 379
Enter Deck 379
Getting Decked 380
Routing 381
www.it-ebooks.info
■ CONTENTS
xiii
Middleware using Modules 382

Deck Internals 384
Request and Response 384
The Filtered Model 384

Dispatching 385
The Router 385
The Wrap-Up 385
The Wrap-Up to Conquer All Wrap-Ups 386
■Appendix: Resources 387
JavaScript 387
MooTools 387
■Index 389

www.it-ebooks.info
■ CONTENTS
xiv
Foreword

I began working on MooTools in 2005, and, after a year of development, I released the very first version
to the public. MooTools slowly gained popularity, ascending to its current position as one of the top
JavaScript frameworks.
MooTools, however, has a rather steep learning curve and a very big codebase. It was never written
with absolute beginners in mind, so users are often intimidated about trying to learn it. This is
unfortunate; they’re missing out on the great power and customizability MooTools offers, simply
because it looks scary.
It is not all MooTools’ fault, of course. There’s a distinct lack of useful information available on the
subject, though I must admit that MooTools itself hasn’t done enough to correct the situation. People
who want to learn the framework are left to their own devices—and that can get really at times.
Fortunately, that’s where this book comes in. Pro JavaScript with MooTools will take you on a journey
from the building blocks of JavaScript, through the prototypal concepts, to the very inner workings of
MooTools. By the time you’re finished reading it, MooTools will hold no more secrets from you.
When I think about the best MooTools articles I have ever read on the Web, Mark’s blog, Keetology,
comes immediately to mind. Mark has been writing awesome JavaScript and MooTools material for
years, in articles (like his “Up the Moo herd” series) and in actual code (Raccoon!). His blog is a must-

read for anyone wanting to learn or expand his knowledge of MooTools, or JavaScript in general.
Pro JavaScript with MooTools isn’t simply a well-written technical book. This book thoroughly
explains how object-oriented programming works in JavaScript, and then gradually takes advantage of
your newly acquired knowledge to explain how MooTools operates, and how you can build awesome
stuff with it.
And awesome stuff is what we want you to build! MooTools is no longer an obscure framework that
sprang from a simple effects library. It’s now a full-fledged development tool with a great set of core
developers, an active and growing community, and a huge roll of user-developed applications and extensions.
But development doesn’t end with the recent successes. While this book is about MooTools 1.3, the
most recent release, it is also a preparation of sorts for version 2.0. MooTools 1.3 reflects the direction
we’re heading in the future—toward a better, faster, and more powerful MooTools. We’re working to
make the strong parts of the framework even stronger, and we’re going to improve the parts that need
improvement.
However, we want you to share in these exciting developments, and the first step toward that is
learning more about MooTools. You don’t need to be an expert to learn MooTools, as this book will show
you. All you need is a little patience, creativity—and a whole lot of milk.
Back in 2005, MooTools was just a small framework I created for fun and experimentation. It never
occurred to me that it would eventually become the subject of a book, a book whose range, I must say, is
as impressive as its depth. It makes me proud of what MooTools has achieved.
Things are just gonna get more awesome from here…
Valerio Proietti
MooTools Founder and Lead-Developer

www.it-ebooks.info

xv
About the Author

■ Mark Joseph Obcena is a freelance software developer, graphic designer, and writer
from Manila, Philippines. Popularly known as keeto online, Mark is a big fan of open

source development and regularly contributes to several open source projects,
including MooTools where he’s a member of the official Community Team. He’s
currently experimenting with new programming languages while working on several
CommonJS projects, which are available from his Github page, and he sometimes
gets bullied by the MooTools community into writing a post for his web site, Keetology
().
Mark also owns a cat named Shröddy, who may or may not exist.
www.it-ebooks.info
■ CONTENTS
xvi
About the Technical Reviewer

■ Simo Kinnunen, originally from Helsinki, lives in Tokyo, where he combines the study of the Japanese
language with being a web expert and JavaScript hacker. He is also a Zend engineer, and he spent quite a
large part of this spare time building a rather complicated web text replacement hack called cufón.
www.it-ebooks.info

xvii
Acknowledgments
I’ve often thought of myself as a one-man show: Mark, the Developer for Every Occasion™. This book,
however, is not mine alone. A lot of people have contributed in one way or another to make this book
possible, and I’d like to take a piece of it to thank them.
First, I want to give a big thank-you to Valerio Proietti, MooTools Founder and Lead Developer, who
has not only given his time to read early drafts of the work, but has also graced this book with a foreword.
You, sir, are truly awesome.
I’d also like to thank the MooTools team—the builders, the contributors, and the creators—who
have tirelessly given their love to the framework. This book would literally not have been possible if not
for the great work that you’ve put into MooTools. Special thanks to Christoph, Djamil, William, David,
and Thomas, who have given their input, pings, and thumbs-up for the book.
A thank-you also goes out to the members of the MooTools community, especially the regulars of

the #mootools IRC channel. Your constant need for updates about the book and unending
encouragement drove me to make this work worthy of the highlights. Thanks and []/ are also due to the
regulars of the “other” mootools IRC channel: Jabis, Michael, Graham, and Rud. You guys are all
awesome.
Of course, I won’t forget to thank Simo, my dear technical reviewer, who has given his time and
effort in reviewing the drafts of this work. Thank you for putting up with my dangling semicolons.
Chocolates and thank-yous are sent to Tokyo for you.
Another round of cheers and claps are also given to the people at Apress who believed enough in
this work to put their time into it. To Frank, thank you for giving me the chance to broadcast my ideas to
the world, and thank you for believing that I could pull off this work. To Mary and Ben, thank you for
putting up with my haphazard writing styles and weird submission schedule. And to Sharon, thank you
for adding more awesome to my writing.
Of course, I’d also like to give thanks and hugs to my family. To my mom and dad who have always
believed in me in their own quirky way, to my siblings Christine and Jan Raleigh who are now learning
the value of being connected, and to my aunt and uncle who have stood by me like a second set of
parents, thank you.
Finally, I’d like to give the biggest thanks to three people by dedicating parts of the book to them.
Part I is dedicated to my friend Garrick Cheung. Without you, this book would have never been
started. Thank you for the input, the critiques and the ideas. You are a great man, an awesome person,
and a very good friend. To Happiness.
Part II is dedicated to my very good friend Tim Wienk. Without you, this book would never have
been completed. Thank you for listening to my rants, thank you for keeping me company, thank you for
keeping me sane, and thank you for being a good friend. To Friendship.
And Part III is dedicated to P.E.M. Without you, I would have never gotten the courage to find
happiness. Thank you for showing me what’s wrong, what’s changing, and what’s possible. I’ll always be
your Marquito. To Love.

www.it-ebooks.info
■ CONTENTS
xviii

Preface
The universe, perhaps, is just a crazy runtime environment with sparse documentation and seemingly
random side effects, and life is nothing more than a program written in a language called “Universcript.”
I conclude that this might be the case because, when I decided to invoke my audition method in the fall
of 2008 to try out for the role of Moritz Stiefel in a local production of Spring Awakening, I never
expected that it would return a Book object.
Fortunately, not all things are that quirky. The universe might think that it’s a great idea to take my
botched audition and turn it into a writing opportunity—an API decision I fully approve, by the way—but
most programming languages behave more predictably. Some languages behave predictably well, some
languages behave predictably well with some exceptions, and some languages behave predictably weird.
The fascinating thing, though, is that a language’s predictability often has less to do with the
language itself and more to do with its users. The more we learn about a programming language, the
more predictable it becomes. The key, then, isn’t coding blindly and whining (quite loudly for some)
about a language’s apparent shortcomings, but learning, experimenting, and applying. The quirks will
stay quirky, but at least now we can appreciate their quirkiness.
This book is about JavaScript as it relates to the MooTools framework. Like any other language,
JavaScript’s predictability has a lot to do with the people who code with it. While it is pretty predictable,
JavaScript does have some quirks and unique features that might not be apparent at base level.
Unfortunately, a lot of us who proudly proclaim to be JavaScript developers don’t take time to learn the
language enough to appreciate these quirks and features.
A big part of this problem, surprisingly, comes from the popularity of frameworks. JavaScript’s
almost prodigal-son-like comeback into the limelight of web development has brought forth a slew of
libraries and frameworks that promise an easier experience when working with the language. While
most of them do deliver on the promise, it comes with the cost of dependency: developers get so
comfortable with a framework that they forget there’s a powerful language underneath the abstraction.
This book tries to address this particular issue for the MooTools framework. MooTools is in the
unique position of being one of the more popular frameworks that extend and improve JavaScript rather
than bury it in the guise of an API. MooTools works with native JavaScript, uses native JavaScript, and
feels like native JavaScript. MooTools users, therefore, are exposed to the power of JavaScript at every
level—all they have to do is look at it.

If you’re looking for a recipe book, a how-to book, or a book of source code that you can copy and
paste into your next application, I’m afraid this is not that book. This book is all about exploring
JavaScript and looking at how JavaScript is used for the internals of the MooTools framework. This book
will show you how the features of JavaScript are used inside the framework, and how they come together
to create the very powerful set of APIs we know as MooTools.
In essence, this book is an extension and expansion of the Up the MooTools Herd series I previously
wrote for my blog. As with that series, this book is not aimed at beginners, but at intermediate and
advanced users. So, if you’re new to MooTools or JavaScript, I suggest you put this book on your to-read
list and grab a beginner’s book first.
This book is divided into three parts. The first part is all about JavaScript as ECMAScript, and
focuses on the native features of the language—functions, objects, and types—and the subsystems
www.it-ebooks.info
■ PREFACE
xix
inside MooTools that work with these parts. The second part of the book focuses on JavaScript in the
browser and explores subjects such as elements, events, and animation. Finally, the last part of this book
is a short exploration of JavaScript outside the browser and gives an introduction to CommonJS and
MooTools using Deck.
As you’ll learn in the next chapter, MooTools is divided into two main projects: MooTools Core and
MooTools More. In writing this book, I’ve decided to focus solely on MooTools Core, so there’s no
mention of any of the features or extensions found in MooTools More. Also, I’ve limited myself to
MooTools version 1.3 for this book, so any features from or incompatibilities with previous versions are
not mentioned.
And with those words out of the way, it’s time for us to start our exploration. It’s best that we begin
with the opening credits and get to know our dramatis personae. So if you’re ready, let’s meet the cast:
JavaScript and MooTools.
www.it-ebooks.info
■ CONTENTS
xx












www.it-ebooks.info
P A R T I



Exploring JavaScript and
MooTools
www.it-ebooks.info
2
www.it-ebooks.info
C H A P T E R 1

■ ■ ■
3
JavaScript and MooTools
Before we begin our exploration of how to get the most out of JavaScript using the powerful MooTools
framework, let’s focus a little on JavaScript and MooTools individually. We’ll also talk about the
JavaScript developer’s toolkit, and what you need to develop applications in JavaScript.
JavaScript
JavaScript started out as a small language called Mocha, which was created by Brendan Eich back in May

of 1995. Mocha was designed for scripting web pages, and the plan was to bundle it with Netscape’s
Navigator browser. Before the browser’s release, though, Netscape acquired a trademark license from
Sun Microsystems to use the name “Java” and the language was renamed to JavaScript. This move was
somewhat political on Netscape’s part: the release of JavaScript coincided with the new Navigator
support for Java, a popular programming language, and the name JavaScript was chosen to market the
language as a new and powerful programming language.
This marketing ploy, although somewhat disingenuous since JavaScript and Java bear no relation
except for a very superficial similarity in naming conventions and some syntax, was quite successful and
JavaScript started gaining traction among web developers. This led Microsoft to create a similar
implementation for its Internet Explorer browser, which was released in August of 1996. Microsoft
named its language JScript in order to bypass having to license the name Java from Sun Microsystems.
Netscape sought standardization for the language and submitted it to Ecma International for work
on the specification, and in June 1997, the first version of ECMAScript was adopted by the Ecma General
Assembly. The name ECMAScript was a compromise: None of the parties involved in the
standardization wanted to donate their trademark, so Ecma decided to invent a new name for the
language.
■ Note ECMAScript is the real name of the language as it’s described by the Ecma standards and specification;
JavaScript and JScript are dialects that have extra features that may not be compatible with the standard. The
JavaScript language and its development are now handled by Mozilla, and JScript continues to be developed by
Microsoft. For the most part, this book is about ECMAScript, but we’ll use the name JavaScript throughout since
it’s the more popular name.
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×