contents foreword xv preface xvii acknowledgments xviii about this book xix about the cover illustration xxiii 1.3 Benefits of SPAs over traditional web applications 12 1.4 Rethinking wh
Trang 1Emmit A Scott, Jr
F OREWORD BY Burke Holland
Understanding single-page web applications
Trang 2SPA Design and Architecture
Trang 3ii
Trang 4SPA Design and
Architecture Understanding single-page web applications
EMMIT A SCOTT, JR.
M A N N I N G
SHELTER ISLAND
Trang 5For 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
©2016 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: Dan Maharry
20 Baldwin Road Technical development editor: Joel Kotarski
Copyeditor: Sharon WilkeyProofreader: Linda RecktenwaldTypesetter: Marija TudorCover designer: Marija Tudor
ISBN: 9781617292439
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 20 19 18 17 16 15
Trang 6To my three beautiful children, Ana Carolina, David, and Sofía Thanks for all the smiles, hugs, and unconditional love.
You are forever in my heart.
Trang 7vi
Trang 8brief contents
P ART 1 T HE BASICS .1
1 ■ What is a single-page application? 3
2 ■ The role of MV* frameworks 22
3 ■ Modular JavaScript 52
P ART 2 C ORE CONCEPTS .83
4 ■ Navigating the single page 85
5 ■ View composition and layout 106
6 ■ Inter-module interaction 129
7 ■ Communicating with the server 156
8 ■ Unit testing 186
9 ■ Client-side task automation 209
Trang 9viii
Trang 10contents
foreword xv preface xvii acknowledgments xviii about this book xix about the cover illustration xxiii
1.3 Benefits of SPAs over traditional web applications 12 1.4 Rethinking what you already know 14
1.5 Ingredients of a well-designed SPA 15
Organizing your project 15 ■ Creating a maintainable, loosely coupled UI 17 ■ Using JavaScript modules 18 ■ Performing SPA navigation 19 ■ Creating view composition and
layout 19 ■ Enabling module communication 20
Trang 112.3 Why use an MV* framework? 44
Separation of concerns 45 ■ Routine tasks simplified 46 Productivity gains 47 ■ Standardization 47
Scalability 48
2.4 Choosing a framework 48 2.5 Chapter challenge 50 2.6 Summary 51
3.1 What is a module? 53
Module pattern concepts 53 ■ The module’s structure 54 The revealing module pattern 55
3.2 Why modular programming? 56
Avoiding name collisions 56 ■ Protecting your code’s integrity 65 ■ Hiding complexity 67 ■ Reducing the impact
of code changes 68 ■ Organizing your code 68 Understanding disadvantages of the module pattern 69
3.3 The module pattern dissected 69
Achieving privacy 69 ■ Creating the public API 70 Allowing for global imports 73 ■ Creating the module’s namespace 73
3.4 Module loading and dependency management 74
Script loaders 74 ■ Asynchronous Module Definition 75 Using AMD modules with RequireJS 77
3.5 Chapter challenge 81 3.6 Summary 81
Trang 12P ART 2 C ORE CONCEPTS .83
4 Navigating the single page 85
4.1 What is a client-side router? 86
Traditional navigation 86 ■ SPA navigation 86
4.2 Routes and their configuration 88
Route syntax 90 ■ Route entries 90 ■ Route parameters 91 Default routes 93
4.3 How do client-side routers work? 93
The fragment identifier method 94 ■ The HTML5 History API method 95 ■ Changes for the HTML5 History API
method 97
4.4 Putting it all together: implementing routing in SPAs 98
The faculty list (default route) 99 ■ The main contact route 101 ■ Faculty office hours (parameterized route) 102
4.5 Chapter challenge 104 4.6 Summary 105
5 View composition and layout 106
5.1 Introducing our project 107 5.2 Reviewing layout design concepts 108
Views 108 ■ Regions 109 ■ View composition 110 Nested views 111 ■ Routes 112
5.3 Considering alternatives for advanced composition and
layout 113
Pros 113 ■ Cons 114
5.4 Designing the application 114
Designing the base layout 115 ■ Designing the default content 117 ■ Using a view manager for complex designs 122 Creating nested views with their own states 125
5.5 Chapter challenge 127 5.6 Summary 128
6 Inter-module interaction 129
6.1 Review of module concepts 131
Modules encapsulate code 131 ■ APIs provide controlled access
to internal functionality 133 ■ SRP means designing with a single purpose 134 ■ Code reuse helps your project scale 135
Trang 136.2 Inter-module interaction methods 136
Inter-module interaction through dependencies 136 Dependency method pros and cons 138 ■ Inter-module interaction through publish/subscribe 138 ■ Pub/sub pros and cons 141
6.3 Project details 142
Searching 144 ■ Displaying product information 150
6.4 Chapter challenge 155 6.5 Summary 155
7 Communicating with the server 156
7.1 Understanding the project requirements 158 7.2 Exploring the communication process 158
Choosing a data type 158 ■ Using a supported HTTP request method 159 ■ Converting the data 160
7.3 Using MV* frameworks 162
Generating requests 162 ■ Processing results with callbacks 165 ■ Processing results with promises 166 Promise error handling 171
7.4 Consuming RESTful web services 172
What is REST? 172 ■ REST principles 172 ■ How MV* frameworks help us be RESTful 174
7.5 Project details 174
Configuring REST calls 174 ■ Adding product items to the cart 177 ■ Viewing the cart 179 ■ Updating the cart 181 Removing products from the cart 183
7.6 Chapter challenge 184 7.7 Summary 184
8 Unit testing 186
8.1 Understanding the project 187 8.2 What is a unit test? 187
Benefits of unit testing 188 ■ Creating better unit tests 189
8.3 Traditional unit testing 192
Getting started with QUnit 193 ■ Creating your first unit tests 196 ■ Testing code built with MV* objects 200 Testing changes to the DOM 205 ■ Adding other testing frameworks to the mix 206
Trang 148.4 Chapter challenge 208
8.5 Summary 208
9 Client-side task automation 209
9.1 Common uses for task runners 210
Live browser reloads 210 ■ Automatic JavaScript and CSS preprocessing 211 ■ Automatic code analysis from linters 211 Continuous unit testing 211 ■ File concatenation 212 Code minification 212 ■ Continuous integration 212
9.2 Choosing a task runner 212
9.3 Our project 213
Introducing Gulp.js 214 ■ Creating your first task 215 Creating a code analysis task 216 ■ Creating a browser-reload task 218 ■ Automating unit testing 220 ■ Creating a build process 222
9.4 Chapter challenge 227
9.5 Summary 227
Trang 15xiv
Trang 16foreword
In 1991, Tim Berners-Lee launched the world’s first website, which ran on a program
he named the WorldWideWeb Two years later, he would release the source code forthe WorldWideWeb and the world itself would never be the same You can still see thatfirst web page at info.cern.ch
Since 1991, the web has experienced unprecedented popularity At 24 years old,it’s still the most widely used technology in the world It runs on all operating systems,all hardware platforms, and nearly all mobile devices in some form or fashion Theprogram that makes this all possible is the almighty web browser
Traditionally, web browsers were simply middlemen They would fetch data from aserver, display it, take data back to the server, and get more data to display But today’sweb browsers, while still true to the original principals of the web, are far more com-plex than anyone could ever have imagined back then
The humble browser has graduated into a full-fledged runtime for applications ofall sizes These are applications that don’t have to be installed, can be accessed fromanywhere, and run everywhere This is the holy grail for developers Being able todeploy one codebase that runs everywhere and is always up to date is an opportunitytoo good to pass up No other technology can make this boast
Riding on the success of the web platform is the ubiquity of JavaScript—a languagecreated in 10 days that’s now the most used programming language in the world.Developers have embraced JavaScript, and that has opened up doors to new types ofapplications that we never would have dreamed possible in a web browser
These new applications, often called single-page applications (SPAs), run almostentirely in the browser, and they introduce a whole new set of principles, patterns, andproblems The broad appeal of the web has resulted in a Cambrian explosion of Java-Script and CSS frameworks; so many that it is daunting at best to try to find the needle
of success in the haystack of frameworks
Trang 17That, dear reader, is why this book is so important
For the past four years, I’ve worked at Telerik as a developer advocate focusing onthe Kendo UI JavaScript library I’ve watched countless JavaScript frameworks comeand go The hype reaches critical mass, and then the next big thing shows up, and thedevelopers who are actually building solutions on these fads are left to pick up thepieces It often leaves me wondering when it will settle down and we can focus on theone “right way” to build this new generation of rich client applications
The raw truth is that there is no “right way” to do anything There is only the waythat works for your project and your skill set There is only the way that makes youmost productive and, ultimately, most successful
In order to find that way in the world of SPAs, it’s imperative to understand the damental principles behind the SPA concept itself Learning a framework will not besufficient and will ultimately leave you short and wanting more A deep understanding
fun-of the core concepts on which a successful SPA rests will enable you to make the rightdecisions with confidence and to know how to build the last 20% when your JavaScriptframework of choice takes you only 80% of the way there
This book will be your guide It’s for experts and novices alike While reading it, Ifound myself learning basics that I had hastily glossed over, as well as getting newinsight into terminology that I thought I had a good grasp of but only partially (and insome cases incorrectly) understood The insight and explanations contained in thesepages are not just academic but also practical and hands-on, showing you how to build
an SPA and addressing real-world implementations head-on while discussing relevantSPA frameworks
I’m generally skeptical of books that try to tackle a concept as big as that of SPAs,but this is one of the few reads that somehow manages to take a very complex topicand break it down into easily understandable and digestible pieces
It is without hesitation that I provide my full recommendation for this book—eachand every page
BURKE HOLLAND DIRECTOR OF DEVELOPER RELATIONS
TELERIK
Trang 18preface
Many of the projects I’ve worked on have been long-running efforts taking a year ormore to build Then, of course, there were updates and additional phases to completeafter that Because these types of projects take so long, technology grows by leaps andbounds in the meantime By the time I was ready to start the next project, I’d have toreevaluate my tech stack because things had changed so much
It was when my team and I were gearing up for our most recent single-page cation project that I had the idea to write this book My director had given us the greenlight to research the “best of breed” for the technologies we wanted to use So we beganevaluating various solutions and creating small proof-of-concept applications
While going through this process again, I was reminded of the difficulties in siftingthrough the sheer volume of information available to us these days It also occurred to
me how daunting this must be for those new to creating single-page applications
So I set out to write a book that would not only summarize what’s involved in ing an SPA but also give a nice introduction to some of the libraries and frameworksused to create them Additionally, I wanted the book to be straightforward and easy todigest, yet give enough technical details so that you can actually build an SPA whenyou’ve finished reading it
Thanks for taking this journey with me I hope you’ll find this book to be an pensable guide to single-page application development
Trang 19acknowledgments
This is my first book, so as you can imagine it was quite overwhelming at times I wasvery fortunate, though, to have three extraordinary people in my corner who consis-tently went above and beyond the call of duty to help mold and shape this book: DanMaharry, my development editor; Joel Kotarski, my technical development editor; andAndrew Gibson, my technical proofreader They are an amazing team to work withand I can’t thank them enough
Thank you, too, Sharon Wilkey, for the wonderful job as copyeditor, and François Morin, for lending a hand as the Java/Spring technical proofreader
I’d also like to thank the numerous other people at Manning who made this bookpossible: Marjan Bace, Michael Stephens, Bert Bates, Maureen Spencer, Kevin Sulli-van, Mary Piergies, Candace Gillhoolley, Rebecca Rinehart, Ana Romac, Toni Bowers,and Linda Recktenwald, as well as the unsung heroes who worked so hard to bringthis effort to fruition
Special thanks to Burke Holland for writing the book’s foreword I’m a huge fan ofBurke’s work and his writing and feel honored that he agreed to write this
Thanks to the reviewers who read this book in its various stages of development:Alain Couniot, Anirudh Prabhu, Bruno Sonnino, David Schmitz, Fernando MonteiroKobayashi, Johan Pretorius, John Shea, Maqbool Patel, Philippe Vialatte, Rajesh Pillai,Shrinivas Parashar, Trevor Saunders, Viorel Moisei, and Yogesh Poojari
Thanks also to my family: my wife Rosalba, my daughter Ana Carolina, my sonDavid, my other daughter Sofía, and my mom Lucy Words just aren’t enough to thankyou for all the love, support, and encouragement you gave me throughout thisendeavor
To all my friends and colleagues, both at work and elsewhere, thank you for yourencouragement and support as well
Trang 20about this book
This book was written to give you an introductory look at what it takes to create asingle-page application The book not only introduces you to frameworks and tech-nologies for creating an SPA but also shows you how to unit test them and how to auto-mate client-side development and build-related tasks
Because part of the process of creating an SPA is deciding what your technologystack will look like, the book compares various approaches used by today’s leadingJavaScript frameworks One of the reasons why so many frameworks exist is thatthere’s no single correct way to build an application By comparing different frame-works, you can better decide what’s right for you and your next project
Each chapter of the book includes a complete, working application I’ve tried tokeep things interesting yet not overwhelming I’m not a fan of long-running examplesthat fill half a book with pages and pages of source code to wade through So Idecided to create a separate project for each chapter I also tried to keep each exam-ple as small and to the point as possible while still being interesting and relevant tothe concepts and topics for the chapter
Roadmap
Part 1: The basics
■ Chapter 1 introduces you to the overall SPA concept From the beginning you’llstart learning important concepts and how SPAs are different from traditionalweb applications You’ll get a clear, concise definition accompanied by an over-view of how the various pieces and parts of an SPA fit together
■ Chapter 2 dives deeper, introducing you to a family of JavaScript frameworksknown as MV* frameworks and their role in the creation of a single-page appli-cation The chapter talks about the commonalities among frameworks, as well
Trang 21as how they’re different The end-of-chapter project is written three differentways, each with a different MV* framework so you can see different architecturalstyles in practice
■ In chapter 3, you’ll get acquainted with modular programming You’ll see hand through examples and the chapter’s project the reasons you should beusing modules in your SPA We’ll also break down the module pattern’s syntaxand walk through it step by step We’ll top off the chapter with an introduction
first-to module loading and AMD modules
Part 2: Core concepts
■ Chapter 4 gives you a crash course on client-side routing You’ll get a down of how routing works under the covers and see how various frameworksapproach routing You’ll also get an understanding of how client-side routingaffects the application’s state
break-■ Chapter 5 introduces you to layout design and view composition in an SPA.We’ll start with simple designs and work our way up to more complicated oneswith complex routes Additionally, we’ll touch on advanced layout topics, likeworking with nested views and sibling views
■ In chapter 6 we’ll talk about inter-module communication What’s the good ofcreating modules if they can’t talk to each other, right? You’ll not only see dif-ferent approaches to inter-module communication but also get a feel for modu-lar application design
■ Chapter 7 looks at the role of the server in an SPA environment Although theclient is still the focus, you’ll see how your SPA communicates with the serverand how to handle results from your server calls The chapter examines resulthandling from the standpoint of both callbacks and the use of promises You’llalso see how MV* frameworks help you with these tasks At the end of the chap-ter, you’ll get a brief introduction to REST and see how your SPA can consumeRESTful services
■ Chapter 8 is an overview of unit testing JavaScript applications, specifically SPAs.Don’t worry if you’ve never done any unit testing on the client We’ll take thisslow and easy and go through the basics step by step
■ Finally, in chapter 9, you’ll see how client-side task automation helps you both
in development and in creating a build process You’ll get clear pictures of themost common types of tasks for each scenario and see them in action in thecode for the end-of-chapter project
The appendices are meant to complement the chapters Appendix A is a walk-through
of the complete source code for all three versions of the project for chapter 2 dix B and appendix C complement chapter 7 Appendix B is an overview of theXMLHttpRequest API, and appendix C is a summary of the server-side calls for thechapter’s project Although the chapter is written deliberately so that you can usethe server-side language of your choice, appendix C additionally includes a guide to
Trang 22the Spring MVC code that was used in the downloadable source Appendix D is a simpleguide for installing Node.js and Gulp.js, which you’ll need if you want to try out thecode for chapter 9
Audience
This book assumes you have at least basic knowledge of JavaScript, HTML, and CSS It’salso helpful if you have some level of web development experience, although this isn’t
a requirement This book does, however, target those who have little or no experience
in the development of single-page applications or have created SPAs but not using thetechnologies described in this book
Code conventions and downloads
Source code in listings or in text appears in a fixed-width font like this to rate it from ordinary text Code annotations accompany the listings, highlightingimportant concepts
Source code for the examples in this book can be downloaded from the lisher’s website at www.manning.com/books/spa-design-and-architecture
pub-Software and hardware requirements
If you’re using a recent Mac OS X or Windows computer and a modern browser (forexample, Firefox, Safari, or Chrome), you should have no trouble with any of theexamples For any special software requirements, you’ll find directions in the chap-ter/appendix itself
Because most of the examples dynamically fetch HTML files, you may need to setcertain privileges in your browser if you’re running the example locally (versus using
a server) Please see the readme.txt file in the downloadable source for the projectfor details
If you want to try the example for chapter 7, you’ll need to use some type of serverand some type of server-side language Everyone has their preferences, so it’s left to you
to decide what you want to use I used Java/Spring MVC and include a mini guide to ting that set up If you’re using something else, I describe the server-side calls andobjects conceptually so you can re-create them using the technology of your choice
get-Author Online
Purchase of SPA Design and Architecture includes free access to a private web forum run
by Manning Publications where you can make comments about the book, ask cal questions, and receive help from the author and from other users To access theforum and subscribe to it, please go to www.manning.com/books/spa-design-and-
registered, what kind of help is available, and the rules of conduct on the forum Manning’s commitment to our readers is to provide a venue where a meaningfuldialog between individual readers and between readers and the author can take place
Trang 23It’s not a commitment to any specific amount of participation on the part of theauthors whose contribution to the Author Online forum remains voluntary (andunpaid) We suggest you try asking the author some challenging questions lest hisinterest stray!
The Author Online forum and the archives of previous discussions will be ble from the publisher’s website as long as the book is in print
accessi-About the author
Emmit Scott is a senior software engineer and architect withmore than 17 years of experience in creating web-based appli-cations He’s developed large-scale applications for education,banking, and telecommunications His hobbies include read-ing (especially Jim Butcher novels), playing the guitar (was ahead banger back in the day), and spending as much time aspossible with his children
Trang 24about the cover illustrationThe figure on the cover of SPA Design and Architecture is captioned “Habit of a Young Turk of Quality in 1700.” The illustration is taken from Thomas Jefferys’ A Collection of the Dresses of Different Nations, Ancient and Modern, London, published between 1757
and 1772 The title page states that these are hand-colored copperplate engravings,heightened with gum arabic Thomas Jefferys (1719–1771), was called “Geographer toKing George III.” He was an English cartographer who was the leading map supplier
of his day He engraved and printed maps for government and other official bodiesand produced a wide range of commercial maps and atlases, especially of NorthAmerica His work as a mapmaker sparked an interest in local dress customs of thelands he surveyed and mapped, and which are brilliantly displayed in this four-volumecollection
Fascination with faraway lands and travel for pleasure were relatively new ena in the late 18th century and collections such as this one were popular, introduc-ing both the tourist as well as the armchair traveler to the inhabitants of othercountries The diversity of the drawings in Jefferys’ volumes speaks vividly of theuniqueness and individuality of the world’s nations some 200 years ago Dress codeshave changed since then and the diversity by region and country, so rich at the time,has faded away It is now often hard to tell the inhabitant of one continent fromanother Perhaps, trying to view it optimistically, we have traded a cultural and visualdiversity for a more varied personal life Or a more varied and interesting intellectualand technical life
At a time when it is hard to tell one computer book from another, Manning brates the inventiveness and initiative of the computer business with book coversbased on the rich diversity of regional life of two centuries ago, brought back to life byJeffreys’ pictures
Trang 25cele-xxiv
Trang 26Part 1 The basics
you’ll need to know before developing your first single-page web application
In chapter 1, we’ll talk about what an SPA is in very clear terms It’s important
to know what this type of architecture involves and why you might choose it overthat of a traditional web application
Keeping your application’s code base clean and maintainable becomes cal when working within the context of a single page Chapter 2 compares differ-ent styles of JavaScript framework that help you achieve that goal The chapterframes the discussion with an introduction to the three architectural patternsthat heavily influenced these frameworks: MVC, MVP, and MVVM The chapterthen progresses into how the same application must change based on the style offramework that’s implemented
In chapter 3, you’ll get a crash course on the module pattern and how it willchange the way you think about organizing your JavaScript code Using this pat-tern, you’ll be able to create functions and variables as you normally would butwithin the cozy confines of a structure that mimics classic encapsulation in otherlanguages As you’ll find out in this chapter, modular programming is crucial for
a successful SPA
Trang 272 C
Trang 28This chapter covers
■ The definition of a single-page application (SPA)
■ An overview of the basic elements of an SPA
■ The benefits of SPAs over traditional web
applications
Trang 294 C 1 What is a single-page application?
The stage was set in the early 2000s A brand-new way of thinking about web-pagedesign came about when the AJAX movement started to gain steam It began with aninteresting, yet obscure, ActiveX control in Microsoft’s Internet Explorer browser,used to send and receive data asynchronously These humble beginnings eventuallyled to a revolution, when the control’s functionality was officially adopted by themajor browser vendors as the XMLH ttp R equest (XHR) API
Developers who began to merge this API with JavaScript, HTML, and CSS obtainedremarkable results The blending of these techniques became known as AJAX, or Asyn-chronous JavaScript and XML AJAX’s unobtrusive data requests, combined with thepower of JavaScript to dynamically update the Document Object Model (DOM), andthe use of CSS to change the page’s style on the fly, brought AJAX to the forefront ofmodern web development
Piggybacking off this successful movement, the SPA concept takes web ment to a whole new level by expanding the page-level manipulation techniques ofAJAX to the entire application Additionally, the patterns and practices commonlyused in the creation of an SPA can lead to overall efficiencies in application design,code maintenance, and development time Having a successful implementation of asingle-page application, though, will be greatly impacted by your understanding ofSPA architecture
As with most emerging solutions, single-page application design comprises a ety of approaches Varying opinions by today’s experts, plus a multitude of competinglibraries and frameworks, can make finding the right solution for your SPA projectchallenging The more you know going into it, the more successful you’ll be in find-ing the implementation that’s right for you and your development goals That’s whyI’ll start by providing a clear understanding of an SPA and its benefits Over the course
vari-of the book, you’ll examine each facet vari-of SPA development by using a style of Script frameworks commonly called MV* frameworks.
Java-1.1 SPA in a nutshell
In an SPA, the entire application runs as a single web page In this approach, the sentation layer for the entire application has been factored out of the server and ismanaged from within the browser To get a better idea of what this looks like, you’llreview a couple of illustrations
pre-Not everything is MV*
Our discussion of SPAs in this book is limited to MV* frameworks (and you’ll learnmore about them in chapter 2) It’s important to make this distinction up front, how-ever, because other approaches can be used to create an SPA, including using React(https://facebook.github.io/react) or Web Components (a W3C specification for a set
of standards for component-based web development), for example
Trang 30SPA in a nutshell
First, let’s take a look at a web application that’s not an SPA Figure 1.1 shows a largeweb application that uses a traditional server-side design
With this design, each request for a new view (HTML page) results in a round-trip
to the server When fresh data is needed on the client side, the request is sent to theserver side On the server side, the request is intercepted by a controller object insidethe presentation layer The controller then interacts with the model layer via the ser-vice layer, which determines the components required to complete the model layer’stask After the data is fetched, either by a data access object (DAO) or by a service
HTML views returned, causing full-page refresh
Business layer
Business logic
and workflows
Business objects/entities
Data layer
Data sources Web services
Data access
objects Service agents
Views created and managed on the server
Figure 1.1 In a traditional web application, each new view (HTML page)
is constructed on the server
Trang 316 C 1 What is a single-page application?
agent, any necessary changes to the data are then made by the business logic in thebusiness layer
Control is passed back to the presentation layer, where the appropriate view is sen Presentation logic dictates how the freshly obtained data is represented in theselected view Often the resulting view starts off as a source file with placeholders, wheredata is to be inserted (and possibly other rendering instructions) This file acts as a kind
cho-of template for how the view gets stamped whenever the controller routes a request to it After the data and view are merged, the view is returned to the browser Thebrowser then receives the new HTML page and, via a UI refresh, the user sees the newview containing the requested data
MV*
framework
Service layer Service
interfaces
Service implementations
Business layer Business logic
and workflows
Business objects/entities
Data layer
Data sources Web services
Data access objects Service agents
Transactions via AJAX (XHR + DOM manipulation) never require refresh
Figure 1.2 In an SPA, the presentation layer moves to the client-side code, and transactions never require a browser refresh
Trang 32The overall SPA design is nearly the same as the traditional design The keychanges are as follows: no full browser refreshes, the presentation logic resides in theclient, and server transactions can be data-only, depending on your preference fordata rendering.
1.1.1 No browser refreshes
In an SPA, views aren’t complete HTML pages They’re merely portions of the DOMthat make up the viewable areas of the screen After the initial page load, all the toolsrequired for creating and displaying views are downloaded and ready to use If a newview is needed, it’s generated locally in the browser and dynamically attached to theDOM via JavaScript No browser refreshes are ever needed
1.1.2 Presentation logic in the client
Because our presentation logic is mostly client side in an SPA, the task of combiningHTML and data is moved from the server to the browser As on the server side, sourceHTML contains placeholders where data is to be inserted (and possibly other render-ing instructions) This client-side template is used as a basis for stamping out newviews in the client It’s not template HTML for a complete page, though It’s for onlythe portion of the page the view represents
The heavy lifting of routing to the correct view, combining data with the HTMLtemplate, and managing a view’s lifecycle is typically delegated to a third-party Java-
Script file commonly referred to as an MV* framework (sometimes called an SPA work) Chapter 2 covers templates and MV* frameworks in detail
frame-1.1.3 Server transactions
In an SPA, several approaches can be used to render data from the server Theseinclude server-side partial rendering, in which snippets of HTML are combined withdata in the server’s response This book focuses on an alternative approach, in whichrendering is done on the client and only data is sent and received during businesstransactions This is always done asynchronously via the XHRAPI The data-exchangeformat is typically JavaScript Object Notation (JSON), though it doesn’t have to be.Even using client-side rendering, though, the server still plays a vital role in the SPA.Chapter 7 reviews the role of the server in more detail
Even if you’re already using a server-side design pattern such as troller (MVC) to separate views, data, and logic, reconfiguring your MVC frameworkfor use with SPAs is relatively easy Therefore, frameworks such as ASP.NET MVC orSpring MVC can still be used with an SPA
Trang 33Model-View-Con-8 C 1 What is a single-page application?
1.2 A closer look
Now that you have a bird’s-eye view of the SPA, let’s break it down a little further Let’stalk about what’s going on in the presentation layer now that it’s moved to thebrowser Because upcoming chapters provide more detail, I’ll keep this discussion at ahigh level
1.2.1 An SPA starts with a shell
The single-page part of the SPA refers to the initial HTML file, or shell This single HTMLfile is loaded once and only once, and it serves as the starting point for the rest of theapplication This is the only full browser load that happens in an SPA Subsequent por-tions of the application are loaded dynamically and independently of the shell, with-out a full-page reload, giving the user the perception that the page has changed Typically, the shell is minimal in structure and often contains a single, empty DIV tagthat will house the rest of the application’s content (see figure 1.3) You can think of thisshell HTML file as the mother ship and the initial container DIV as the docking bay The code for the shell has some of the basic starting elements of a traditional webpage, such as a HEAD and BODY The following listing illustrates a basic shell file
Listing 1.1 Example SPA shell
Shell starts empty
Title
Figure 1.3 The HTML shell is the beginning structure It has no content yet, only an
empty DIV tag.
Load the application’s style sheets
Initial container DIV
Trang 34A closer look
The initial container DIV can have
child containers beneath it if the
application’s viewable area is divided
into subsections The child
contain-ers are often referred to as regions,
because they’re used to visually
divide the screen into logical zones
(see figure 1.4)
Regions help you divide the
view-able area into manageview-able chunks of
content The region container DIV is
where you tell the MV* framework to
insert dynamic content It’s worth
noting, though, that other paradigms are used by frameworks not covered in thisbook React, for example, uses DOM patching rather than the replacement of particu-lar regions
1.2.2 From traditional pages to views
The “pages” of the application aren’t pages at all, at least not in the traditional sense
As the user navigates, the parts of the screen that appear to be pages are actually
inde-pendent sections of the application’s content, called views Chapter 2 covers views in
detail For now, it’s enough to know that the view is a portion of the application thatthe end user sees and interacts with
Imagining the difference between the average web page and the view of an SPA can
be difficult To help you visualize the difference, take a look at the following figures.Figure 1.5 shows a simple website composed of two web pages As you can see, bothweb pages of the traditional site contain the complete HTML structure, including theHEAD and BODY tags
Title Header region Header view Sidebar region
Sidebar view View 1
Trang 3510 C 1 What is a single-page application?
Figure 1.6 shows the same website as an SPA The SPA “pages” are only HTML ments If the content of the viewable area of the screen changes, that’s the equivalent
frag-of changing pages in a traditional website
When the application starts, the MV* framework inserts view 1 When the user igates to what appears to be a new page, the framework is swapping view 1 for view 2.Chapter 4 covers SPA navigation in detail
nav-1.2.3 The birth of a view
If sections (or views) of the application aren’t part of the initial shell, how do theybecome part of the application? As mentioned previously, the various sections of theSPA are presented on demand, usually as a result of user navigation The skeletalHTML structure of each section, called a template, contains placeholders for data.
JavaScript-based libraries and frameworks, commonly referred to as MV*, are used tomarry data and at least one template This marriage ultimately results in the final view(see figure 1.7) All the screen’s content beyond the shell gets placed into separateviews
Figure 1.6 In an SPA design, one complete HTML file contains placeholders for the HTML
fragments stored in view files.
{"firstName":"Karen",
"lastName":"Tate"}
+
<div>
First Name: {{firstName}} <br>
Last Name: {{lastName}}
Trang 36A closer look
The completed view is attached to the DOM, as needed, either directly under the tial container DIV, as illustrated in figure 1.8, or in one of the regions if there are any
ini-1.2.4 View swapping for zero reload navigation
All of this happens without having to refresh the shell So instead of getting served anew static page for every navigation request, the SPA can display new content without
a disruption for the user For a particular part of the screen, content of one view ismerely replaced by the content of another view This gives the illusion that the pageitself is changing as the user navigates (see figure 1.9) Navigation without a reload is akey feature of the single-page application that gives it the feel of a native application
DIV or one of its regions.
Trang 3712 C 1 What is a single-page application?
The interesting thing about navigation in an SPA is that, to the user, it looks like thepage is changing The URL will look different, and even the Back button can be used
to take the user to the previous “page.”
Keep in mind that the heavy lifting of creating and managing the views in the ent is handled by MV* frameworks In chapter 2, you’ll dissect their various parts to get
cli-an even clearer picture
1.2.5 Fluidity through dynamic updates
Another defining aspect of the SPA is how data from the server can be retrieved chronously and inserted dynamically into the application So not only does the pagenot reload during navigation, it also doesn’t reload while requesting and receivingserver data This, too, gives the appearance and feel of a native application The tech-niques of AJAX make this all possible I began this chapter by talking about the naturalevolution of web development and how AJAX played a pivotal role in the development
asyn-of the SPA concept So I’d be remiss if I didn’t include AJAX as part of the SPA definition Previously, I explained in great detail how the page, or view, is swapped dynamicallyduring navigation Domain data from the server, or from cache, can also be added andremoved in the same fashion The retrieval of the data, which happens silently in thebackground, can happen in parallel with other data requests After the data is fetched,it’s combined with the HTML template, and the view is updated in real time The ability
to update the page right in front of the user’s eyes without even as much as a flickergives the application a certain fluidity and sleekness that can’t be attained with a tradi-tional web application Chapter 7 covers accessing data in greater detail
1.3 Benefits of SPAs over traditional web applications
The web browser is still a great way to distribute software because of its “thinness,”ubiquity, and standardized environment End users will already have a web browser.It’s also great for software updates, because the updates happen on the server instead
of users having to worry about the installation process Unfortunately, jarring, page reloads, content being duplicated with every request, and heavy transaction pay-loads have all diminished the benefits of browser-delivered content
Web-based customer interactions are far from over, though Just the opposite istrue, and SPAs are at the forefront of this user-experience revolution The idea of thesingle-page application was born out of our desire to give end users the best experi-ence possible Here are some reasons you should consider single-page applicationarchitecture:
■ Renders like a desktop application, but runs in a browser—The SPA has the ability toredraw portions of the screen dynamically, and the user sees the updateinstantly Because the SPA downloads the web-page structure in advance, there’s
no need for the disruptive request to get a new page from the server This issimilar to the experience a user would get from a native desktop application;
Trang 38Benefits of SPAs over traditional web applications
therefore, it “feels” more natural An advantage over even the desktop tion, the SPA runs in the browser, making its native-like, browser-based environ-ment the best of both worlds
applica-■ Decoupled presentation layer—As mentioned previously, the code that governs how
the UI appears and how it behaves is kept on the client side instead of theserver This leaves both server and client as decoupled as possible The benefithere is that each can be maintained and updated separately
■ Faster, lightweight transaction payloads—Transactions with the server are lighter
and faster, because after initial delivery, only data is sent and received from theserver Traditional applications have the overhead of having to respond with thenext page’s content Because the entire page is re-rendered, the contentreturned in traditional applications also includes HTML markup Asynchro-nous, data-only transactions make the operational aspect of this architectureextremely fast
■ Less user wait time—In today’s web-centric world, the less time a user has to wait
for the page to load, the more likely the person is to stay on the site and return
in the future Because the SPA loads with a shell and a small number of ing files and then builds as the user navigates, application startup is perceived
support-as being quick As the previous points state, screens render quickly andsmoothly, and transactions are lightweight and fast These characteristics alllead to less user wait time Performance isn’t just a nice-to-have It equates toreal dollars when online commerce is involved A study by Walmart that was
published in Web Performance Today1 indicated that for every 100 ms of mance improvement, incremental revenue grew by up to 1% In Walmartterms, that’s huge
perfor-■ Easier code maintenance—Software developers are always looking for better ways
to develop and maintain their code base Traditionally, web applications are abit of a Wild West kind of environment, where HTML, JavaScript, and CSS can
be intertwined into a maintenance nightmare Add in the ability to combineserver-side code with the HTML source (think Active Server Pages or JavaServerPages scriptlets) and you’ve got a giant, steaming pile of goo As you’ll see inupcoming chapters, MV* frameworks like the ones covered in this book help usseparate our code into different areas of concern JavaScript code is kept where
it needs to be—out of the HTML and in distinct units With the help of party libraries and frameworks (for example, Knockout, Backbone.js, and
third-AngularJS), the HTML structure for an area of the screen and its data can bemaintained separately The amount of coupling between the client and theserver is dramatically reduced as well
1 business-metrics-at-walmart-com
Trang 39www.webperformancetoday.com/2012/02/28/4-awesome-slides-showing-how-page-speed-correlates-to-14 C 1 What is a single-page application?
1.4 Rethinking what you already know
In a single-page web application, you use the
same languages that you normally use when
creating a web application: HTML, CSS, and
JavaScript There’s no browser plugin
required and no magic SPA language to learn
HTML and CSS continue to be the primary
building blocks for the UI’s structure and
lay-out, whereas JavaScript is still the cornerstone
for interactivity and UI logic (see figure 1.10)
The difference to the user is in how the
application will feel using SPA architecture
The navigation feels more like a native
desk-top application, delivering a smoother, more
enjoyable experience This difference for you,
the developer, is that to create an application
that functions within a single HTML page, you’ll need to rethink your normalapproach to web development
As mentioned in the previous section, in an SPA, the application is broken intoindependent sections, or views So you’ll no longer create entire pages in which com-mon elements, such as a header or a main menu, are repeated Even the common sec-tions are views in an SPA You’ll also have to stop thinking about the layout ofindividual pages and start thinking in terms of view placement in the available realestate of the screen As it turns out, this is easy after you get the hang of it Global lay-out areas, such as a main menu, remain fixed throughout the user experience Sharedareas of the screen, such as the center content well, are reused by the application toswap the various views (as well as entire regions) during user navigation
To the end user, though, the application can look exactly like a traditional web
application As figure 1.11 illustrates, it can have a header, a sidebar, or any other cal web-page element
typi-SPA client
CSS:
styles and layout
JavaScript: behavior HTML:
structure
Figure 1.10 CSS, HTML, and JavaScript are the building blocks for the single-page application There’s no special language to learn and no browser plugins required.
Header region Header view
so that it looks exactly like a traditional web page.
Trang 40Ingredients of a well-designed SPA
On the JavaScript side, you’ll continue to code as you normally would, with one majorexception Because you’re dealing with a single page that doesn’t refresh, simpleglobal scope for variables and functions won’t suffice You’ll divide your code into
workable units and house it in special functions called modules that have their own
scope This frees you from having to create all your variables and functions in theglobal namespace
Communication with the server in an SPA is via AJAX Though the name impliesXML, most modern SPAs use AJAX techniques but use JSON as the preferred data-exchange format It’s an ideal format for the SPA because it’s lightweight and com-pact, and its syntax is well-suited for describing object structure But AJAX should benothing new to most developers Even traditional web applications typically use atleast some AJAX
Your overall design will revolve around keeping all the SPA code easily manageableand decoupled from other areas of concern But don’t worry about any extra complex-ity Once you get the hang of the unusual syntax of the module pattern, your life as adeveloper will get easier I present modular programming in detail later in the bookand use variants of the module design pattern in all the examples So no worries—you’ll see it so much that by the end of the book it’ll be second nature to you!
1.5 Ingredients of a well-designed SPA
If you researched the topic of single-page applications before picking up this book,you may have felt a little overwhelmed at your choices As you’ve seen so far, the SPAisn’t a single technology It’s a federation of technologies that work together to createthe finished product There are almost as many libraries and frameworks as there areopinions about the correct approach to take So admittedly, trying to find the pieces
of the puzzle that not only fit together but also fit the needs of your project and thepreferences of your team can be rather daunting
The good news is that there’s a method to the madness If you look at the page application concept as a whole, it can be broken into a list of categories that canfit any style of solution you adopt as your own
single-1.5.1 Organizing your project
Having a well-organized project isn’t complicated, but it does require some thoughtand shouldn’t be taken for granted Fortunately, no hard-and-fast rules apply to direc-tory structures The general rule of thumb is that you should use whatever style worksfor the development team A couple of common ways to organize your files are by fea-ture and by functionality
Grouping similar files by feature is somewhat akin to organizing code in a piled language, such as Java, into packages It’s clean, discourages the cross-referenc-ing of features, and visually segments files related to a particular feature within theproject’s file structure The following listing illustrates how the client code for anapplication might be arranged using this style