(Ebook) Programming JavaScript Applications: Robust Web Architecture with Node, HTML5, and Modern JS Libraries by Eric Elliott ISBN 9781491950296, 1491950293 instant download
(Ebook) Programming JavaScript Applications: Robust Web Architecture with Node, HTML5, and Modern JS Libraries by Eric Elliott ISBN 9781491950296, 1491950293 instant download
https://ebooknice.com/product/programming-javascript-applications-
robust-web-architecture-with-node-html5-and-modern-js-libraries-4952508
Eric Elliott
Programming JavaScript Applications
by Eric Elliott
Copyright © 2014 Eric Elliott. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected].
Editors: Simon St. Laurent and Meghan Blanchette Indexer: Lucie Haskins
Production Editor: Kara Ebrahim Cover Designer: Randy Comer
Copyeditor: Eliahu Sussman Interior Designer: David Futato
Proofreader: Amanda Kersey Illustrator: Rebecca Demarest
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Programming JavaScript Applications, the image of an argali, and related trade dress are trade‐
marks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-491-95029-6
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Minimize Side Effects 10
Function Definition 12
Named Function Expressions 14
Lambdas 16
Immediately Invoked Function Expressions 18
Method Context 20
Function Scope 22
Hoisting 22
Closures 25
Method Design 27
Named Parameters 28
iii
Function Polymorphism 29
Generics and Collection Polymorphism 32
Method Chaining and Fluent APIs 35
Functional Programming 36
Stateless Functions (aka Pure Functions) 38
Partial Application and Currying 40
Asynchronous Operations 41
Callbacks 41
Promises and Deferreds 42
Conclusion 44
3. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Classical Inheritance Is Obsolete 48
Fluent-Style JavaScript 51
Prototypes 53
Delegate Prototypes 53
Prototype Cloning 56
The Flyweight Pattern 57
Object Creation 59
Factories 61
Prototypal Inheritance with Stamps 64
Conclusion 69
4. Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Principles of Modularity 72
Interfaces 73
The Module Pattern 77
Asynchronous Module Definition 79
Plug-Ins 81
Node-Style Modules 82
npm 84
ES6 Modules 86
Building Client-Side Code with CommonJS, npm, Grunt, and Browserify 87
Defining the App 87
Feature Implementation 90
Bundling and Deployment 93
Conclusion 98
5. Separation of Concerns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Client-Side Concerns 100
Module Management 101
Events 106
iv | Table of Contents
Model View Controller/MV* 114
Presentation and DOM Manipulation 117
Server-Side Concerns 125
Getting Started with Node and Express 125
Conclusion 134
7. Logging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Debugging 151
Server Operations 153
Security 153
Auditing 154
Business Analytics 154
Viral Factor 155
Logging Checklist 155
Logging Requests 156
Logging Errors 160
Sample Log Output 162
Logging Service Alerts 165
Logging Goals 166
Profiling and Instrumentation 166
Logging Client-Side Events 167
Deciphering Data 168
Conclusion 169
Table of Contents | v
HTML as an API Media Type 185
Jade 185
Jiron 187
Responsive APIs 189
Optimizing for Speed 191
Conclusion 192
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
vi | Table of Contents
Preface
Introduction
There are many books on the web technologies covered in this publication. However,
there are precious few on JavaScript that can be recommended to somebody who wants
to learn how to build a complete JavaScript application from the ground up. Meanwhile,
almost every new tech startup needs knowledgeable JavaScript application developers
on staff. This book exists for one purpose: to help you gain the knowledge you need to
build complete JavaScript applications that are easy to extend and maintain.
This book is not intended to teach you the basics of JavaScript. Instead, it’s designed to
build on your existing knowledge and discuss JavaScript features and techniques that
will make your code easier to work with over time. Normally, as an application grows,
it becomes increasingly difficult to add new features and fix bugs. Your code becomes
too rigid and fragile, and even a small change could necessitate a lengthy refactor. If you
follow the patterns outlined in this book, your code will remain flexible and resilient.
Changes to one piece of code won’t negatively impact another.
This book will focus primarily on client-side architecture, although it will also cover
server-side topics, such as basic RESTful APIs and Node. The trend is that a great deal
of the application logic is getting pushed to the client. It was once the case that the server
environment would handle things like templating and communication with vendor
services. Now, it’s common to deal with both of those jobs inside the browser.
In fact, a modern JavaScript application does almost everything a traditional desktop
app would do completely in the browser. Of course, servers are still handy. Server roles
frequently include serving static content and dynamically loaded modules, data persis‐
tence, action logging, and interfacing with third-party APIs.
vii
We’ll cover:
viii | Preface
JavaScript: The Good Parts, and pay special attention to Appendix A so that you can
learn from the mistakes made by more experienced JavaScript developers.
Unit Testing
It’s difficult to overstate the importance of unit testing. Unit tests are used throughout
this book. By the time you reach the end, you should be accustomed to seeing and writing
them. As you practice the concepts you read about, start by writing the tests first. You’ll
get a better understanding of the problem domain, and you’ll be forced to think through
the design for your solution and the interface you create for it. Designing for unit tests
also forces you to keep your code decoupled. The discipline of writing testable, decou‐
pled code will serve you well your entire career.
For a reference on unit tests and code style, see Appendix A.
Preface | ix
Safari® Books Online
Safari Books Online is an on-demand digital library that lets
you easily search over 7,500 technology and creative refer‐
ence books and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down‐
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub‐
lishers, sign up for free at http://my.safaribooksonline.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://bit.ly/programming-jsa
To comment or ask technical questions about this book, send email to:
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
x | Preface
Thanks
Thanks @JS_Cheerleader for encouragement and lots of great JavaScript links.
Thanks to Brendan Eich for his tireless work to drive JavaScript and the web forward.
Thanks to the team at O’Reilly. To Simon St. Laurent, who immediately recognized the
value of the book and provided a lot of encouragement along the way. To Brian McDo‐
nald, whose valuable feedback made this a much better book. To Meghan Blanchette
for keeping the momentum alive. Thanks to the following individuals for their great
technical feedback:
• César Andreu
• James Halliday (Substack)
• Hugh Jackson
• Ramsey Lawson
• Shelley Powers
• Kyle Simpson
• Kevin Western
A special thank you to the people who have contributed to the open source projects
written for this book, and to all of the open source contributors who make programming
JavaScript applications a much better experience every single day. As software devel‐
opers, we are all standing on the shoulders of giants.
Preface | xi
CHAPTER 1
The JavaScript Revolution
1
In 2004, Google launched Gmail. Initially applauded because it promised users nearly
infinite storage for their email, Gmail also brought a major revolution. Gone were the
page refreshes. Under the hood, Gmail was taking advantage of the new Ajax technology,
creating a single-page, fast, and responsive web application that would forever change
the way that web applications are designed.
Since that time, web developers have produced nearly every type of application, in‐
cluding full-blown, cloud-based office suites (see Zoho.com), social APIs like Facebook’s
JavaScript SDK, and even graphically intensive video games.
All of this is serving to prove Atwood’s Law: “Any application that can be written in
JavaScript, will eventually be written in JavaScript.”
Advantages of JavaScript
JavaScript didn’t just luck into its position as the dominant client-side language on the
Web. It is actually very well suited to be the language that took over the world. It is one
of the most advanced and expressive programming languages developed to date. The
following sections outline some of the features you may or may not be familiar with.
Performance
Just-in-time compiling: in modern browsers, most JavaScript is compiled, highly opti‐
mized, and executed like native code, so runtime performance is close to that of software
written in C or C++. Of course, there is still the overhead of garbage collection and
dynamic binding, so it is possible to do certain things faster; however, the difference is
generally not worth sweating over until you’ve optimized everything else. With Node.js
(a high-performance, evented, server-side JavaScript environment built on Google’s
highly optimized V8 JavaScript engine), JavaScript apps are event driven and non‐
blocking, which generally more than makes up for the code execution difference be‐
tween JavaScript and less dynamic languages.
Objects
JavaScript has very rich object-oriented (OO) features. The JSON (JavaScript Object
Notation) standard used in nearly all modern web applications for both communication
and data persistence is a subset of JavaScript’s excellent object-literal notation.
JavaScript uses a prototypal inheritance model. Instead of classes, you have object pro‐
totypes. New objects automatically inherit methods and attributes of their parent object
through the prototype chain. It’s possible to modify an object’s prototype at any time,
making JavaScript a very flexible, dynamic language.
Syntax
The JavaScript syntax should be immediately familiar to anybody who has experience
with C-family languages, such as C++, Java, C#, and PHP. Part of JavaScript’s popularity
is due to its familiarity, though it’s important to understand that JavaScript behaves very
differently from all of these under the hood.
JavaScript’s object-literal syntax is so simple, flexible, and concise, it was adapted to
become the dominant standard for client/server communication in the form of JSON,
which is more compact and flexible than the XML that it replaced.
First-Class Functions
In JavaScript, objects are not a tacked-on afterthought. Nearly everything in JavaScript
is an object, including functions. Because of that feature, functions can be used anywhere
you might use a variable, including the parameters in function calls. That feature is often
used to define anonymous callback functions for asynchronous operations, or to create
higher order functions (functions that take other functions as parameters, return a func‐
tion, or both). Higher-order functions are used in the functional programming style to
abstract away commonly repeated coding patterns, such as iteration loops or other in‐
struction sets that differ mostly in the variables or data they consume.
Good examples of functional programing include functions like .map(), .reduce(),
and .forEach(). The Underscore.js library contains many useful functional utilities.
For simplicity, we’ll be making use of Underscore.js in this book.
Events
Inside the browser, everything runs in an event loop. JavaScript coders quickly learn to
think in terms of event handlers, and as a result, code from experienced JavaScript
developers tends to be well organized and efficient. Operations that might block pro‐
cessing in other languages happen concurrently in JavaScript.
If you click something, you want something to happen instantly. That impatience has
led to wonderful advancements in UI design, such as Google Instant and the ground‐
breaking address lookup on The Wilderness Downtown. (“The Wilderness Downtown”
is an interactive short film by Chris Milk set to the Arcade Fire song, “We Used To Wait.”
Advantages of JavaScript | 3
It was built entirely with the latest open web technologies.) Such functionality is powered
by Ajax calls that do their thing in the background without slowing down the UI.
Reusability
JavaScript code, by virtue of its ubiquity, is the most portable, reusable code around.
What other language lets you write the same code that runs natively on both the client
and the server? (See “Getting Started with Node and Express” on page 125 to learn about
an event-driven JavaScript environment that is revolutionizing server-side
development.)
JavaScript can be modular and encapsulated, and it is common to see scripts written by
six different teams of developers who have never communicated working in harmony
on the same page.
Infrastructure
Infrastructure can come in many flavors and have lots of different caching mechanisms.
Generally, it consists of (back to front):
• A data store
• A virtual private network (VPN) or firewall (to protect the data store from unau‐
thorized access)
• A black box JSON RESTful Web Service Layer
• Various third-party APIs
Most of these components are self explanatory, but there are some important points that
you should be aware of concerning the storage and communication of application data.
The data store is just like it sounds: a place to store your application data. This is com‐
monly a relational database management system (RDBMS) with a Structured Query
Language (SQL) API, but the popularity of NoSQL solutions is on the rise. In the future,
it’s likely that many applications will use a combination of both.
As you can see, this format is nearly identical to JavaScript’s object-literal syntax, with
a couple important differences:
• All attributes names and string values must be enclosed in double quotes. Other
values may appear in their literal form.
• JSON records cannot contain circular references.
• JSON cannot contain functions.
*****
*****
*****
*****
*****
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com