(Download PDF) Javascript Application Design A Build First Approach 1St Edition Nicolas Bevacqua Online Ebook All Chapter PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

JavaScript Application Design A Build

First Approach 1st Edition Nicolas


Bevacqua
Visit to download the full and correct content document:
https://textbookfull.com/product/javascript-application-design-a-build-first-approach-1s
t-edition-nicolas-bevacqua/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Practical Modern JavaScript Dive into ES6 and the


Future of JavaScript Nicolás Bevacqua

https://textbookfull.com/product/practical-modern-javascript-
dive-into-es6-and-the-future-of-javascript-nicolas-bevacqua/

JavaScript Patterns Build Better Applications with


Coding and Design Patterns 1st Edition Stefanov Stoyan

https://textbookfull.com/product/javascript-patterns-build-
better-applications-with-coding-and-design-patterns-1st-edition-
stefanov-stoyan/

Creating a Web Site Design and Build Your First Site


1st Edition Greg Rickaby

https://textbookfull.com/product/creating-a-web-site-design-and-
build-your-first-site-1st-edition-greg-rickaby/

JavaScript Recipes: A Problem-Solution Approach 1st


Edition Russ Ferguson

https://textbookfull.com/product/javascript-recipes-a-problem-
solution-approach-1st-edition-russ-ferguson/
Pharmaceutical quality by design a practical approach
First Edition Gibson

https://textbookfull.com/product/pharmaceutical-quality-by-
design-a-practical-approach-first-edition-gibson/

Practical Azure Application Development: A Step-by-Step


Approach to Build Feature-Rich Cloud-Ready Solutions
1st Edition Thurupathan Vijayakumar (Auth.)

https://textbookfull.com/product/practical-azure-application-
development-a-step-by-step-approach-to-build-feature-rich-cloud-
ready-solutions-1st-edition-thurupathan-vijayakumar-auth/

Regression Analysis and Its Application: A Data-


Oriented Approach First Edition Richard F. Gunst

https://textbookfull.com/product/regression-analysis-and-its-
application-a-data-oriented-approach-first-edition-richard-f-
gunst/

JavaScript Domain Driven Design 1st Edition Fehre

https://textbookfull.com/product/javascript-domain-driven-
design-1st-edition-fehre/

Pro TypeScript: application-scale javascript


development Second Edition Fenton

https://textbookfull.com/product/pro-typescript-application-
scale-javascript-development-second-edition-fenton/
A Build First Approach

Nicolas Bevacqua
FOREWORD BY Addy Osmani

MANNING
JavaScript Application Design
JavaScript
Application Design
A Build First Approach

NICOLAS BEVACQUA

MANNING
SHELTER ISLAND
iv

For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com

©2015 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15 percent recycled and processed without elemental chlorine.

Manning Publications Co. Development editor: Susan Conant


20 Baldwin Road Technical development editor: Douglas Duncan
PO Box 761 Copyeditor: Katie Petito
Shelter Island, NY 11964 Proofreader: Alyson Brener
Technical proofreaders: Deepak Vohra
Valentin Crettaz
Typesetter: Marija Tudor
Cover designer: Marija Tudor

ISBN: 9781617291951
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 20 19 18 17 16 15
To Marian, for withstanding the birth of this book,
your unconditional love, and your endless patience.

I love you!

Will you marry me?


vi
brief contents
PART 1 BUILD PROCESSES ........................................................ 1
1 ■
Introduction to Build First 3
2 ■
Composing build tasks and flows 23
3 ■
Mastering environments and the development workflow 50
4 ■
Release, deployment, and monitoring 71

PART 2 MANAGING COMPLEXITY ........................................... 97


5 ■
Embracing modularity and dependency management 99
6 ■
Understanding asynchronous flow control methods in
JavaScript 131
7 ■
Leveraging the Model-View-Controller 166
8 ■
Testing JavaScript components 211
9 ■
REST API design and layered service architectures 251

vii
viii BRIEF CONTENTS
contents
foreword xv
preface xvii
acknowledgments xix
about this book xxi
about the author xxv
about the cover illustration xxvi

PART 1 BUILD PROCESSES ............................................ 1

1 Introduction to Build First 3


1.1 When things go wrong 4
How to lose $172,222 a second for 45 minutes 5
Build First 5 Rites of initiation 6

1.2 Planning ahead with Build First 7


Core principles in Build First 7
1.3 Build processes 9
1.4 Handling application complexity and design 11
1.5 Diving into Build First 15
Keeping code quality in check 16 ■
Lint in the command
line 19
1.6 Summary 22

ix
x CONTENTS

2 Composing build tasks and flows


2.1 Introducing Grunt 24
23

Installing Grunt 26 Setting up your first Grunt task



28
Using Grunt to manage the build process 29
2.2 Preprocessing and static asset optimization 31
Discussing preprocessing 31 Doing LESS 34 ■

Bundling static assets 37 Static asset minification



38
Implementing image sprites 41
2.3 Setting up code integrity 43
Cleaning up your working directory 43 ■
Lint, lint, lint! 44
Automating unit testing 45
2.4 Writing your first build task 46
2.5 Case study: database tasks 47
2.6 Summary 49

3 Mastering environments and the development workflow 50


3.1 Application environments 51
Configuring build distributions 51 Environment-level■

configuration 56 What’s so special about development?



58
3.2 Configuring environments 58
Storing configuration in a waterfall 59 Using encryption to ■

harden environment configuration security 61 Setting ■

environment-level configuration at the OS level 62


Merging configuration as a waterfall in code 64
3.3 Automating tedious first-time setup tasks 65
3.4 Working in continuous development 66
Waste no time, use a watch! 66 Monitoring for changes to the

Node app 67 ■
A text editor that cares 69 Browser refresh ■

is so Y2K 69
3.5 Summary 70

4 Release, deployment, and monitoring 71


4.1 Releasing your application 73
Image optimization 73 Static asset caching 75

Inlining critical above-the-fold CSS 77 Testing before a■

deployment 78
4.2 Predeployment operations 79
Semantic versioning 80 ■
Using changelogs 81 ■
Bumping
changelogs 81
CONTENTS xi

4.3 Deploying to Heroku 82


Deploying builds 85 ■
Managing environments 85
4.4 Continuous integration 86
Hosted CI using Travis 86 ■
Continuous deployments 88
4.5 Monitoring and diagnostics 89
Logging and notifications 89 Debugging Node ■

applications 92 Adding performance analytics 93


Uptime and process management 94


4.6 Summary 95

PART 2 MANAGING COMPLEXITY ................................ 97

5 Embracing modularity and dependency management 99


5.1 Working with code encapsulation 101
Understanding the Single Responsibility Principle 101
Information hiding and interfaces 104 Scoping and this ■

keyword 106 Strict mode 109 Variable hoisting 110


■ ■

5.2 JavaScript modules 111


Closures and the module pattern 111 Prototypal ■

modularity 112 CommonJS modules 113


5.3 Using dependency management 114


Dependency graphs 114 Introducing RequireJS 117

Browserify: CJS in the browser 119 The Angular way 120 ■

5.4 Understanding package management 122


Introducing Bower 122 Big libraries, small

components 124 Choosing the right module system



125
Learning about circular dependencies 126
5.5 Harmony: a glimpse of ECMAScript 6 127
Traceur as a Grunt task 127 ■
Modules in Harmony 128
Let there be block scope 129
5.6 Summary 129

6 Understanding asynchronous flow control methods in


JavaScript 131
6.1 Using callbacks 132
Avoiding callback hell 133 Untangling the callback

jumble 134 Requests upon requests 136 Asynchronous


■ ■

error handling 138


xii CONTENTS

6.2 Using the async library 141


Waterfall, series, or parallel? 141 Asynchronous functional

tasks 145 Asynchronous task queues 147 Flow


■ ■

composition and dynamic flows 147


6.3 Making Promises 150
Promise fundamentals 150 Chaining Promises 153 ■

Controlling the flow 155 Handling rejected Promises 156


6.4 Understanding events 157


Events and the DOM 157 ■
Creating your own event
emitters 158
6.5 Glimpse of the future: ES6 generators 161
Creating your first generator 161 ■
Asynchronicity and
generators 163
6.6 Summary 165

7 Leveraging the Model-View-Controller


7.1 jQuery isn’t enough 167
166

7.2 Model-View-Controller in JavaScript 170


Why Backbone? 170 Installing Backbone 172

Browserifying your Backbone module with Grunt 172


7.3 Introduction to Backbone 174
Backbone views 175 Creating Backbone models

177
Organizing models with Backbone collections 179 ■
Adding
Backbone routers 180
7.4 Case study: the shopping list 183
Starting with a static shopping list 183 This time with remove ■

buttons 185 Adding items to your cart 187 Using inline


■ ■

editing 191 A service layer and view routing 197


7.5 Backbone and Rendr: server/client shared rendering 199


Diving into Rendr 199 Understanding boilerplate in

Rendr 201 A simple Rendr application 203


7.6 Summary 210

8 Testing JavaScript components 211


8.1 JavaScript testing crash course 212
Logical units in isolation 212 Using the Test Anything■

Protocol (TAP) 213 Putting together our first unit test 214

Tape in the browser 214 Arrange, Act, Assert 215


Unit testing 216 Convenience over convention 217



CONTENTS xiii

Case study: unit testing an event emitter 217 Testing the ■

event emitter 218 Testing for the .on method 219


Mocks, spies, and proxies 221 Mocking 222 ■

Introducing Sinon.js 223 Spying on function calls 223


Proxying require calls 224


8.2 Testing in the browser 226
Faking XHR and server communication 227 ■
Case study:
testing DOM interaction 229
8.3 Case study: unit testing the MVC shopping list 238
Testing the view router 238 ■
Testing validation on a view
model 243
8.4 Automating Tape tests 245
Automating Tape tests for the browser 246 ■
Continuous
testing 247
8.5 Integration, visual, and performance testing 247
Integration testing 247 ■
Visual testing 248 ■
Performance
testing 249
8.6 Summary 250

9 REST API design and layered service architectures 251


9.1 Avoiding API design pitfalls 252
9.2 Learning REST API design 253
Endpoints, HTTP verbs, and versioning 254 Requests, ■

responses, and status codes 257 Paging, caching, and■

throttling 260 Documenting an API 263


9.3 Implementing layered service architectures 264


Routing layer 265 Service layer 265 Data layer 265
■ ■

Routing layer 266 Service layer 266 Data layer 267


■ ■

9.4 Consuming a REST API on the client side 267


The request handling layer 268 Shooting down old ■

requests 268 Consistent AJAX error management 269


9.5 Summary 271

appendix A Modules in Node.js 273


appendix B Introduction to Grunt 276
appendix C Picking your build tool 284
appendix D JavaScript code quality guide 293

index 307
xiv CONTENTS
foreword
The process of designing a robust JavaScript web app has gone through a roaring
renaissance in recent years. With the language being used to develop increasingly
ambitious apps and interfaces, this is the perfect time for JavaScript Application Design.
Through concise examples, lessons learned from the field, and key concepts for scal-
able development, Nico Bevacqua will give you a whirlwind tour of taking the process
and design of your apps to the next level.
This book will also help you craft build processes that will save you time. Time is a
key factor in staying productive. As web app developers, we want to make the most of
ours, and a Build First philosophy can help us hit the ground running with clean, test-
able apps that are well structured from the get-go. Learning process workflow and
how to manage complexity are fundamental cornerstones of modern JavaScript app
development. Getting them right can make a massive difference in the long run.
JavaScript Application Design will walk you through automation for the front end. It
covers everything from avoiding repetitive tasks and monitoring production builds to
mitigating the cost of human error through a clean tooling setup. Automation is a big
factor here. If you aren't using automation in your workflow today, you're working too
hard. If a series of daily tasks can be accomplished with a single command, follow
Nico's advice and spend the time you save improving the code quality of your apps.
Modularity is the final crucial concept that can assist with building scalable, main-
tainable apps. Not only does this help ensure that the pieces composing our applica-
tion can be more easily tested and documented, it encourages reuse and focus on
quality. In JavaScript Application Design, Nico expertly walks you through writing modu-

xv
xvi FOREWORD

lar JavaScript components, getting asyncronous flow right, and enough client-side
MVC for you to build an app of your own.
Strap on your seatbelts, adjust your command line, and enjoy a ride through the
process of improving your development workflow.

ADDY OSMANI
SENIOR ENGINEER
WITH A PASSION FOR DEVELOPER TOOLING
GOOGLE
xxviii ABOUT THE COVER ILLUSTRATION
Another random document with
no related content on Scribd:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning of
this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1 with
active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or expense
to the user, provide a copy, a means of exporting a copy, or a means
of obtaining a copy upon request, of the work in its original “Plain
Vanilla ASCII” or other form. Any alternate format must include the
full Project Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt that
s/he does not agree to the terms of the full Project Gutenberg™
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in paragraph
1.F.3, the Project Gutenberg Literary Archive Foundation, the owner
of the Project Gutenberg™ trademark, and any other party
distributing a Project Gutenberg™ electronic work under this
agreement, disclaim all liability to you for damages, costs and
expenses, including legal fees. YOU AGREE THAT YOU HAVE NO
REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF
WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE
PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE
FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving it,
you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or entity
that provided you with the defective work may elect to provide a
replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the
Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and distribution
of Project Gutenberg™ electronic works, harmless from all liability,
costs and expenses, including legal fees, that arise directly or
indirectly from any of the following which you do or cause to occur:
(a) distribution of this or any Project Gutenberg™ work, (b)
alteration, modification, or additions or deletions to any Project
Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many small
donations ($1 to $5,000) are particularly important to maintaining tax
exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.

Project Gutenberg™ eBooks are often created from several printed


editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like