contents preface xv acknowledgments xvi about this book xix about the cover illustration xxiii Containers and layouts at a glance 9 ■ Other containers in action 10 ■ Data-bound views 11
Trang 2Ext JS in Action, Second Edition
Trang 4Ext JS in Action,
Second Edition
JESUS GARCIA GRGUR GRISOGONO JACOB K ANDRESEN
M A N N I N G
SHELTER ISLAND
Trang 5For more information, please contact
Special Sales Department
Manning Publications Co
20 Baldwin Road
PO Box 261
Shelter Island, NY 11964
Email: orders@manning.com
©2014 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 booksare printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine
Manning Publications Co Development editors: Sebastian Stirling, Frank Pohlman
Cover designer: Marija Tudor
ISBN: 9781617290329
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 19 18 17 16 15 14
Trang 67 ■ The data store 147
8 ■ The grid panel 168
9 ■ Taking root with trees 196
10 ■ Drawing and charting 218
11 ■ Remote method invocation with Ext Direct 251
12 ■ Drag-and-drop 269
P ART 3 B UILDING AN APPLICATION 311
13 ■ Class system foundations 313
14 ■ Building an application 337
Trang 8contents
preface xv acknowledgments xvi about this book xix about the cover illustration xxiii
Containers and layouts at a glance 9 ■ Other containers
in action 10 ■ Data-bound views 11 ■ Make like
a tree panel and leaf 13 ■ Form input fields 14 Other widgets 16
1.4 What’s new in Ext JS 4.0 17
Poof goes the adapter layer! 17 ■ New class system 17 Data package 18 ■ Layouts: an explosion of code 19 New docking system 19 ■ Grid panel improvements 19
Trang 9Tree panel now closer to grids 20 ■ Draw and charts 21 New CSS styling architecture 22 ■ New MVC architecture 22 Bundled packaging tool 22
1.5 Downloading and configuring 22 1.6 Take it for a test drive 24
Removing child nodes 35 ■ Using Ajax with Ext.Element 37
2.3 Using templates and XTemplates 38
Using templates 38 ■ Looping with XTemplates 41 Advanced XTemplate usage 42
2.4 Summary 44
3 Components and containers 45
3.1 The Component model 46
XTypes and ComponentManager 47 ■ Component rendering 49
3.2 The component life cycle 50
Initialization 51 ■ Render 53 ■ Destruction 56
Trang 104.2 Displaying window dialogs 77
Building a window 77 ■ Further window configuration 79
4.3 MessageBox 80
Alerting your users 81 ■ Advanced MessageBox techniques 82 Showing an animated wait message box 84
4.4 Components can live in tab panels too 85
Building your first tab panel 86 ■ Tab management methods you should know 89
4.5 Summary 89
5 Exploring layouts 91
5.1 How layout managers work 92
Component layouts 92 ■ Container layouts 92
5.2 The Auto layout 92
5.3 The Anchor layout 94
5.4 The Absolute layout 98
5.5 The Fit layout 99
5.6 The Accordion layout 100
5.7 The Card layout 102
5.8 The Column layout 105
5.9 The HBox and VBox layouts 107
5.10 The Table layout 110
5.11 The Border layout 113
5.12 Summary 117
6 Forms in Ext JS 119
6.1 Basic input fields 120
Input fields and validation 120 ■ Password and file-select fields 123 ■ Building a text area 123 The convenient number field 124
6.2 Type-ahead with the ComboBox 124
Building a local ComboBox 125 ■ Implementing a remote ComboBox 127 ■ The ComboBox deconstructed 130 Customizing your ComboBox 130
6.3 The time field 131
Trang 116.4 The HTML Editor 132
Constructing your first HTML Editor 132 Dealing with lack of validation 133
6.5 Selecting a date 133 6.6 Checkboxes and radio buttons 134 6.7 The form panel 136
Reviewing what you’re building 137 ■ Constructing the fieldsets 137 ■ Creating the tab panel 140
6.8 Data submission and loading 142
Submitting the good old way 142 ■ Submitting via Ajax 143 Loading data into your form 144
6.9 Summary 146
7 The data store 147
7.1 Introducing the data store 148
The supporting classes 148 ■ How data flows 149 All about data proxies 150 ■ Models and readers 152
7.2 Loading and saving data 153
Reading array data 153 ■ Reading JSON data 156 Reading XML data 158
7.3 A store with Writer 159
Validating your model data 161 ■ Syncing your data 163
7.4 Associating data 164 7.5 Summary 167
8 The grid panel 168
8.1 Introducing the grid panel 169
Looking under the hood 169
8.2 Building a simple grid panel 170 8.3 Advanced grid panel construction 172
What you’re building 172 ■ The required data store and model 173 ■ Setting up columns 174 Configuring your advanced grid panel 175 Configuring a container for your grid panel 176 Buffered paginated scrolling 178 ■ Applying event handlers for interaction 180
Trang 128.4 Editing data in the grid panel 183
Enabling the editing plug-in 183 ■ Navigating your editable grid panel 188
8.5 Getting the CRUD in 189
Adding save and reject logic 189 ■ Saving or rejecting your changes 190 ■ Adding create and delete 190 Using create and delete 193
8.6 Summary 195
9 Taking root with trees 196
9.1 Tree panel theory 196
Tree panel keywords 197 ■ Looking under the roots 198
9.2 Planting your first tree panel 198
9.3 Growing dynamic tree panels 201
Creating a remote-loading panel 201 ■ Fertilizing the tree panel 203
9.4 Implementing CRUD on a tree panel 205
Displaying context menus 205 ■ Wiring up the edit logic 209 Tackling delete 213 ■ Creating nodes for your tree panel 215
10.5 Mastering the path 228
10.6 A deep dive into charts 231
10.7 Implementing Cartesian charts 233
Configuring the axes 233 ■ Adding series 236 Improving visual aids 237 ■ Adding custom shapes 240 Multiple series on the same chart 242
10.8 Custom themes 244
10.9 Pie charts 248
10.10 Summary 250
Trang 1311 Remote method invocation with Ext Direct 251
11.1 Making the two ends meet 252 11.2 Ext Direct vs REST 252 11.3 Server-side setup 255
How it works 255 ■ Remote method configuration 255 Routing 256
11.4 Working with remote methods 257
Setting up the router 257 ■ Enabling Ext Direct 259
11.5 Directly invoking remote methods 262 11.6 CRUD-enabled Ext.data.DirectStore 265 11.7 Summary 268
12.1 The drag-and-drop workflow 270
The drag-and-drop life cycle 270 ■ A top-down view of the drag-and-drop classes 271 ■ It’s all in the overrides! 274 Drag-and-drop always works in groups 275
12.2 Drag-and-drop: a basic example 275
Creating a small workspace 275 ■ Configuring items
to be draggable 277 ■ Analyzing the Ext.dd.DD DOM changes 277 ■ Adding the pool and hot tub drop targets 279
12.3 Finishing your drag-and-drop implementation 280
Adding the drop invitation 281 ■ Adding a valid drop 283 Implementing an invalid drop 285
12.4 Using DDProxy 286
Implementing DDProxy and the drop invitation 286
12.5 Drag-and-drop with views 290
Constructing the views 290 ■ Adding drag gestures 294 Applying drop 297
12.6 Drag-and-drop with grid panels 301
Constructing the grid panels 301
12.7 Drag-and-drop with tree panels 304
Constructing the tree panels 305 ■ Enabling drag-and-drop 306 Employing flexible constraints 307
12.8 Summary 310
Trang 1413 Class system foundations 313
13.1 Classic JavaScript inheritance 314
Creating a base class 314 ■ Creating a subclass 315
13.2 Inheritance with Ext JS 317
Creating a base class 317 ■ Creating a subclass 319
13.3 Extending Ext JS components 320
Thinking about what you’re building 321 Extending GridPanel 322 ■ Your extension in action 324
13.4 Plug-ins to the rescue 326
The anatomy of a plug-in 326 ■ Developing a plug-in 327
13.5 Dynamically loading classes with the Ext JS loader 330
Loading everything dynamically 330 ■ Thou shalt require only what’s needed 332 ■ Taking the hybrid approach 333
14.3 Kicking off the Survey app 344
From idea to code 344 ■ Moving to the fast track with Sencha Cmd 345 ■ Bootstrapping Survey 348 Data-driven application model 351 ■ Adding models
to the application 352 ■ Adding data stores 356 Creating the authentication form 357 ■ Plugging in the first controller 359 ■ Survey views 360
Survey controllers 364
14.4 Packaging 370
14.5 Summary 371
Trang 16preface
I started my career in the world of Sencha back in 2006 when the precursor to what isknown as Ext JS today (Sencha’s desktop JavaScript framework) was something of anexperiment Soon after my introduction, I became addicted to the design patternsthat were promoted by the quickly evolving framework But, more importantly, I fell inlove with the thriving community of developers looking to give back
I was inspired by many of the active members in the community, and decided tobecome a contributing member myself, spending tens of hours per week answeringquestions, writing blog posts, and eventually publishing instructional screencasts Timeswere certainly interesting back then, as design patterns emerged from the community
This second edition of Ext JS in Action, originally published in 2010, reflects a new
era of desktop web front-end development that was ushered in by Ext JS 4.0 This sion brought forth an extremely robust class system and offers many capabilities thatextend those of JavaScript Add to that a very well-designed event system, data pack-age, UI, and MVC, and in Ext JS 4.0 you have a powerful framework that will allow you
ver-to develop applications ver-to be used for many years ver-to come
We are delighted to share our knowledge of Ext JS with you and hope you enjoythis journey
—JAY GARCIA
Trang 17acknowledgments
The authors would like to thank the following:
■ The Sencha Community—Without you, this book would simply not havebeen possible
■ Sebastian Sterling—The publication of this book has taken a lot longer than weanticipated As our primary developmental editor at Manning, you challengedour writing and helped us bring out the best content Thank you for all of yourhard work Thanks also to Frank Pohlman, who helped usher this book throughits final stages and hand it off to production
■ The Manning production team—You guys are absolutely amazing! We feel veryfortunate to have had the opportunity to work with you, on this book as well asour previous ones, and we value the work you’ve done through the years Thankyou so very much!
■ Our MEAP (Manning Early Access Program) readers—Thank you for your ful corrections and comments in the Author Online forum
help-■ Our reviewers—They read the manuscript in its various stages during ment and contributed insights and feedback that helped make this a betterbook Thanks to Bradley Meck, Brian Crescimanno, Brian Daley, Brian Forester,Chad Davis, Darragh Duffy, Efran Cobisi, Jeet Marwah, John J Ryan III, LoianeGroner, Mary Turner, Raul Cota, Robby O’Connor, and Todd Hill
develop-■ Doug Warren—Your technical proofread and thorough review of the chaptersand the code during production has proved invaluable to us Thank you!
Trang 18Jay Garcia
Writing this book took a lot of effort on my part, but I certainly wouldn’t have beenable to do it without the help and contributions of others I owe each of the following
a personal thank you:
■ My wife—Erika, this book has been in the works for a few years When peoplecongratulate me, they often don’t recognize that I couldn’t have written thisbook had you not provided the much-needed support for me to do so I loveyou with all of my heart and am very grateful to have you in my life
■ My sons—Takeshi, Kenji: I won’t forget the constant running around the house
as I wrote this book I thank you for your sacrificed time with me to allow me tocomplete it You boys are the reason I work so hard, and I love you very much
■ Mitchell Simoens—I’m grateful to call you my friend Watching your ment both professionally and personally has been something I’ve taken greatpride in Always remember to push the envelope with your knowledge
develop-■ Abe Elias—I have been amazed to see you evolve as you worked through themany years with Sencha to lead a team of top-notch professional engineers.Whenever I talk about great people, you’re one of the names that always comes
to mind Keep staying awesome!
■ Grgur Grisogono—Meeting you has changed my life for the better I’m grateful
to your friendship and look forward to many more years
■ Jacob Andresen—Your contributions to this manuscript have been valuable,and I thank you for the hard work you put in to get chapters cranked out
■ Don Griffin—Thank you for allowing me to take part in conversations ing Sencha Cmd and other Ext JS–related tools
regard-Grgur Grisogono
I want to thank my loving wife Andrea and kids Laurenco and Paulina for their stant support and encouragement They provided me with the resources and the lovethat I needed to generate, channel, and renew energy to write the content for thisbook I’m forever indebted to the incredible reviewers who shared their energy andknowhow to make a much better book for the good of the community
I would also like to extend my gratitude to Modus Create for supporting me andgranting me new challenges that have made me a better professional Special thanks
to Sencha and its core team engineers, who have been incredibly helpful, providinginsight into the latest and greatest to make the content of this book up to date withthe most recent Ext JS and Sencha Cmd upgrades
The most sincere appreciation is due to two of the most prominent Ext JS munity members and tremendous people: my coauthors, Jesus Garcia and JacobAndresen They were a tremendous team to work with, the perfect guides and review-ers, and the never-tiring locomotive that constantly pushed the project forward
Trang 19And finally, I’m forever indebted to my incredible friend, role model, and co-worker,Jay G for his amazing support, energy, and patience His insights have been a constantsource of awe, sharp observations, and great ideas.
Jacob Andresen
First of all, I would like to thank Jesus Garcia for allowing me to tag along on the ride.Contributing to this book has given me the opportunity to study the craft of writingand observe how Jesus has curated the amount of technical detail that has gone intothis book I would also like to thank Grgur Grisogono for the effort he put into thisbook, as well as his work in the international Sencha community
Speaking of the community, there is no escaping Mats Bryntse, Fredric Berling,and Emil Pennlöv here in Scandinavia—thank you for all the good times
Most important of all, thanks to my wife Anita for understanding why I spend allthose long nights programming
Trang 20about this book
The purpose of this book is to inform and educate you about the flexible and ful desktop framework, Ext JS This book is designed to walk you through the basics ofusing this framework all the way through to developing and deploying productionapplications with Sencha Cmd After you’ve read this book, you should be able todevelop robust desktop web applications This revised edition covers the many newfeatures of Ext JS 4.0
power-Who should read this book
This book is intended for developers who want to use Ext JS to create rich desktop webapplications that feel native Although Ext JS is themed and highly customized, thisbook is targeted to those who primarily perform the programming aspect of specifica-tion implementation
We assume that you already have a working understanding of how websites interactwith web servers To be most effective in writing robust and responsive applications,you need a solid background with core technologies like HTML, CSS, JavaScript, andJSON The only time we talk in detail about these core technologies is in chapter 13,where we discuss prototypal inheritance with JavaScript, a prerequisite to the Ext JSclass system
What you’ll need
In the book, we’ll walk you through many hands-on examples In order to get themost out of them, the following items should be set up on your computer:
Trang 21■ A web server—We recommend Apache HTTPD or Microsoft IIS.
■ An intelligent IDE—We recommend Webstorm or Aptana
■ A copy of Sencha Cmd installed—It’s available at
Chapter 2 is designed to get your feet wet with the framework We’ll take a goodlook at how the framework is delivered to you and identify its contents We’ll also walkthrough the basics of DOM manipulation and work our way up to using the Ext JS tem-plate engines, Template and XTemplate, to render data in the DOM
Chapter 3 is about Component and Container, both base classes for the Ext JS UI.We’ll discuss the component lifecycle and look at how to use Container and its utilitymethods to manage and query for child components
Chapter 4 builds on chapter 3 We’ll discuss core UI components such as panels,windows, message boxes, and tab panels These are all fundamental widgets thatextend Container and allow you to present your UIs with more functionality thanContainer provides
Chapter 5 covers the various layout managers that Ext JS provides, which are used
to organize components on screen After reading this chapter, you’ll be able to struct complex user interfaces with the many Ext JS widgets
Chapter 6 revolves around the form panel and the various input fields We’ll look
at how to set up validations with input fields, and you’ll learn how to load and savedata with form panels
Chapter 7 focuses on the Ext JS data package You’ll learn about the core dataclasses—Model, Proxy, Reader, and Store—all of which are used to supply data to vari-ous UI components
Chapter 8 builds on chapter 7, and you’ll learn about the grid panel We’ll explorethe various classes that support the grid panel, and you’ll learn to use many commonimplementation patterns
Chapter 9 is the root source for learning about Ext JS tree panels We’ll dive intohow to use the data TreeStore class to support hierarchical data to the tree panelwidget and end the chapter with tree data manipulation via implementation of anExt JS menu
Trang 22Chapter 10 covers the Ext JS Draw and Charting package You’ll draw simpleshapes as we explore how to draw on a canvas using the Ext JS Draw API Afterward,you’ll learn how to implement the many charts that Ext JS provides
Chapter 11 focuses on direct web remoting with Ext JS We’ll explore what it takes
to integrate server-side logic with the client to allow the server code to dictate APIcalls to the client
Chapter 12 covers drag-and-drop with Ext JS We’ll look at how to implement thebasic drag-and-drop classes and then dive into using drag-and-drop with grids, trees,and data views
Chapter 13 focuses on the Ext JS class system We begin by covering basicJavaScript prototypal inheritance and elevate your knowledge up to developing Ext
JS classes You’ll learn how to extend Ext JS components and develop plug-ins tothe framework
Chapter 14 will take you through what it’s like to develop an application usingSencha Cmd and the Ext JS MVC system You’ll learn how to set up the basic appli-cation scaffolding, develop an app using MVC, and then produce testing and pro-duction builds
Code conventions
All source code in this book is in a fixed-width font like this, which sets it off fromthe surrounding text In many listings, the code is annotated to point out the key con-cepts We have tried to format the code so that it fits within the available page space inthe book by adding line breaks and using indentation carefully Sometimes, however,very long lines include line-continuation markers
Getting the latest examples
The examples in this book are designed to be easy to navigate Each chapter is its ownfolder, with each example named according to the listing it corresponds to
We’ll work to keep the examples up to date as the framework is upgraded Toget the latest version of the examples, you can fork the following GitHub repo:https://github.com/ModusCreateOrg/extjs-in-action-examples You can also download
a zip file with the code examples from the publisher’s website at www.manning.com/ExtJSinActionSecondEdition
Author Online
Purchase of Ext JS in Action, Second Edition includes free access to a private web
forum run by Manning Publications where you can make comments about the book,ask technical questions, and receive help from the authors and from other users
To access the forum and subscribe to it, point your browser to www.manning.com/ExtJSinActionSecondEdition This page provides information on how to get on theforum once you’re registered, what kind of help is available, and the rules of con-duct on the forum
Trang 23Manning’s commitment to our readers is to provide a venue where a meaningfuldialog between individual readers and between readers and the authors can takeplace It’s not a commitment to any specific amount of participation on the part of theauthors, whose contribution to the AO remains voluntary (and unpaid) We suggestyou ask the authors challenging questions lest their interest stray!
About the authors
Jay Garcia is CTO and cofounder of Modus Create, a company focused on ing high-end solutions with Sencha products Jay’s involvement with the world ofSencha started in 2006 Since then, Jay has been focused on knowledge sharingthrough books, blog articles, screencasts, meetups, and conferences His blog is athttp://moduscreate.com/
deliver-Grgur Grisogono is a principal at Modus Create and a web technology evangelist.Grgur has been involved with Ext JS since 2007 and has successfully organized threeSencha-focused conferences in Europe
Jacob Andresen resides in Germany and is an Ext JS enthusiast He works on variousprojects and contributes to the community via blog posts and the Sencha forums
Trang 24Dress codes have changed since then and the diversity by region, so rich at the time,has faded away It is now hard to tell apart the inhabitants of different continents, letalone different towns or regions Perhaps we have traded cultural diversity for a morevaried personal life—certainly for a more varied and fast-paced technological 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 covers based
cele-on the rich diversity of regicele-onal life of two centuries ago, brought back to life by trations from collections such as this one
Trang 26Chapter 1 provides an overview of what’s new with Ext JS 4.0 It also coversthe fundamental concepts and widgets of the framework, and helps you develop
a “Hello World” application Chapter 2 addresses the basics needed for the dation of any Ext JS application, such as initialization, DOM element manipula-tion, and injecting HTML fragment templates with Ajax server data Chapter 3explores components and the life cycle of UI building blocks such as viewports,panels, menus, tabs, data grids, dynamic forms, and stylized pop-up windows, aswell as containers and layout controls that manage child items
After reading the chapters in part 1, you’ll see how Ext JS works from the insideout and be ready to explore the many widgets that compose the Ext JS framework
Trang 28A framework apart
Envision a scenario where you’re tasked to develop an application with many of thetypical user interface (UI) widgets such as menus, tabs, data grids, dynamic forms,and stylized pop-up windows You want something that allows you to programmati-cally control the position of widgets, which means it has to have layout controls.You also want detailed and organized centralized documentation to ease yourlearning curve with the framework Finally, your application needs to look matureand go into beta phase as quickly as possible, which means you don’t have a lot oftime to toy with HTML and CSS Before entering the first line of code for the proto-type, you need to decide on an approach for developing the frontend What areyour choices?
You do some recon on the common popular frameworks and libraries on themarket and quickly learn that all of them can manipulate the DOM, but only two ofthem have mature UI widgets: Yahoo! User Interface (YUI) and Ext JS
This chapter covers
■ Learning what’s new in Ext JS 4.0
■ Obtaining the source code
■ Exploring a “Hello world” example
Trang 29With your first glance at YUI, you might think you needn’t look any further Youplay with the examples and notice that they look mature but aren’t exactly profes-sional quality, which means you’ll need to modify CSS No way Next, you look at thedocumentation It’s centralized and technically accurate, but it’s far from user-friendly You notice all of the scrolling required to locate a method or class Someclasses are even cut off because the left navigation pane is too small
In this chapter, we’ll take a good look at Ext JS, and you’ll learn about some of thewidgets that compose the framework After we finish the overview, you’ll downloadExt JS and take it for a test drive
To develop a rich internet application (RIA) with a set of rich UI controls, you turn toExt JS and find that, out of the proverbial box, Ext JS provides a rich set of DOM utili-ties and widgets Although you can get excited about what you see in the examplespage, it’s what’s under the hood that’s most exciting Ext JS comes with a full suite oflayout management tools to give you full control over organizing and manipulatingthe UI as requirements dictate One layer down exist what are known as the Compo-nent model and Container model, each playing an important role in managing howthe UIs are constructed
Almost all UI widgets in the framework are highly customizable, giving you the option
to enable and disable features, override functions, and use custom extensions andplug-ins One example of a web application that takes full advantage of Ext JS is con-joon Figure 1.1 shows a screenshot of conjoon in action
conjoon is an open source personal information manager and can be consideredthe epitome of web applications developed with Ext JS It uses just about all of theframework’s native UI widgets and demonstrates how well the framework can inte-grate with custom extensions such as YouTubePlayer, LiveGrid, and ToastWindow You’ve learned that Ext JS can be used to create a full-page web application It’squite easy to see that a lot can be achieved using this framework As you’ll soonlearn, the framework is pretty vast, and the API documentation will become yourbest friend
Speaking of the API documentation, let’s switch gears and take a glance at it
Component and Container models
The Component and Container models play a key role in managing UIs with Ext JS andare part of the reason Ext JS stands out from the rest of the Ajax libraries and frame-works The Component model dictates how UI widgets are instantiated, rendered,
and destroyed in what’s known as the component life cycle The Container model trols how widgets can manage (or contain) other child widgets These are two key
con-areas for understanding the framework, which is why we’ll spend a lot of time onthese two topics in chapter 3
Trang 30Looking at Ext JS
1.1.1 Rich API documentation
With the 4.0 version of the framework, the API documentation is new and improved.When opening the API documentation for the first time, you get a sense of the frame-work’s polish Unlike competing frameworks, the Ext JS API documentation uses itsown framework to present a clean and easy-to-use documentation tool that uses Ajax
to provide the documentation
We’ll explore all of the features of the API and talk about some of the componentsused in this documentation tool Figure 1.2 illustrates some of the components used
in the Ext JS API documentation application
The API documentation tool is chock-full of gooey GUI goodness and incorporatessix of the most commonly used widgets, including the text input field, tree panel, tabpanel, panel, and toolbar with embedded buttons
You’re probably wondering what all of these are and what they do Let’s take a moment
to discuss these widgets before we move on
History support
The Ext JS 4.0 documentation now includes browser history support This means thatyou can use the browser’s forward and back buttons to walk up and down your APIdocumentation breadcrumbs
YouTubePlayer extension
ToastWindow extension
LiveGrid extension
Figure 1.1 conjoon is an open source personal information manager that’s a great example of
a web application that uses the Ext JS framework to manage a UI which uses 100 percent of
the browser’s viewport You can download it at http://conjoon.org/.
Trang 31The text input field is a widget that wraps the native browser text input form control,adding features such as validation In the API documentation, it’s used to perform livesearches against the tree panel and is custom styled We’ll talk more about tab panels
in chapter 4
The tree panel widget displays hierarchical data visually in the form of a tree muchlike Windows Explorer displays your hard drive’s folders The tab panel provides ameans to have multiple documents or components on the canvas but allows only one
to be active at a time, though in the API documentation, it displays only one item The panel is a workhorse of Ext JS It’s flexible and contains many areas to displaycontent, including the dock and the content body The dock is where items like tool-bars are typically placed, and the content body is the area where content or child wid-gets are typically rendered In the case of the API documentation, the content bodycontains the documentation for the framework
The Toolbar class provides a means to present commonly used UI components such
as buttons and menus, but it can also contain, as in this case, any of the Ext.form.Fieldsubclasses You can think of the toolbar as a place for the common file-edit-view menusthat you see in popular operating systems and desktop applications
Using the API is a cinch To view a document, click the class node on the tree.Doing so invokes an Ajax request to fetch the documentation for the desired class.Each document for the classes is an HTML fragment (not a full HTML page)
So the documentation is thorough But what about rapid application ment? Can Ext JS accelerate your development cycles?
develop-Text input field
Buttons
Toolbar Tab panel
Tree panel
Panel
Figure 1.2 The Ext JS API documentation contains a wealth of information and is a great resource for learning more about components and widgets.
Trang 32A tour of the Ext JS widgets
1.1.2 Rapid development with prebuilt widgets
Ext JS can help you jump from conception to prototype because it offers many of therequired UI elements already built and ready for integration Having these UI widgetsprebuilt, instead of having to engineer them, saves you a lot of time In many cases, the
UI controls are highly customizable and can be modified to your application’s needs
Although being an expert in web application development isn’t required to developwith Ext JS, developers should have some core competencies before attempting towrite code with the framework
The first of these skills is a basic understanding of Hypertext Markup Language(HTML) and Cascading Style Sheets (CSS) It’s important to have some experiencewith these technologies because Ext JS, like any other JavaScript UI library, uses HTMLand CSS to build its UI controls and widgets Although its widgets may look like andmimic typical modern operating system controls, it all boils down to HTML and CSS inthe browser
Because JavaScript is the glue that holds Ajax together, we recommend you have asolid foundation in JavaScript programming Again, you needn’t be an expert, but youshould have a good grasp of key concepts such as arrays, references, and scope It’s aplus if you’re familiar with object-oriented JavaScript fundamentals such as objects,classes, and prototypal inheritance If you’re new to JavaScript, you’re in luck Java-Script has existed nearly since the dawn of the internet An excellent place to start isW3Schools.com, which offers a lot of free online tutorials and even has sandboxes foryou to play with JavaScript online You can visit them at http://w3schools.com/JS/
If you need to develop code for the server side, you must have a server-side tion for Ext JS to interact with as well as a way to store data To persist data, you’llneed to know how to interact with a database or filesystem via your server-side lan-guage of choice
Naturally, the range of solutions available is quite large For this book, we won’t focus
on a specific language Instead, we’ll use online resources at http://ExtJSinaction.com,where we’ve done the server-side work for you This way, all you have to focus on islearning Ext JS Along the way, we’ll provide specific API URLs for you to use
We’ll begin our exploration of Ext JS with a bird’s-eye view of the framework,where you’ll learn about the categories of functionality
The story of Ext JS main codebase begins in early 2010, during the development ofSencha Touch, the world’s first HTML5 mobile framework (released in November2010) Sencha Touch brought forth the base underpinnings, known as Sencha Plat-form (see figure 1.3), which contains many of the critical features that Ext JS and Sen-cha Touch both use Such common features include DOM and event management,the Component model, and layouts, all of which we’ll be diving into later in this book
Trang 33The Ext JS framework provides not only UI widgets but also a host of other features.These fall into seven major areas of purpose: core, UI components, web remoting,data services, drag-and-drop, draw and charts, and general utilities Figure 1.4 illus-trates the seven areas of purpose.
Knowing what the different areas of purpose are and what they do will give you anedge when developing applications, so we’ll take a moment to discuss them
CORE
The first feature set is the Ext JS core, which comprises many basic features such as Ajaxcommunication, DOM manipulation, and event management Everything else is depen-dent on the core of the framework, but the core isn’t dependent on anything else
DATA SERVICES
The data services section takes care of all your data needs, which include fetching,parsing, and loading information into stores With the Ext JS data services classes youcan read Array, XML, and JavaScript Serialized Object Notation (JSON), which is a
Ext JS Sencha Touch
Sencha Platform
Figure 1.3 Ext JS 4.0 and Sencha Touch both branch off of Sencha Platform, a common base for the Sencha family of HTML5 frameworks.
Trang 34A tour of the Ext JS widgets
data format that’s quickly becoming the standard for client-to-server communication.Stores typically feed UI components
DRAW AND CHARTS
This all-new package encompasses the Ext JS cross-browser drawing engine compatiblewith Vector Markup Language (VML) and Scalable Vector Graphics (SVG) With Draw, youcan generate your own data visualizations, but its primary purpose is to act as a foundationfor the Charting package The Charting package comes complete with many popularcharts including Cartesian (Bar, Line, Column, and so on), Pie, Area, Scatter, and others
DRAG-AND-DROP
Drag-and-drop is like a mini-framework inside Ext JS, where you can apply drop capabilities to an Ext JS component or any HTML element on the page Itincludes all the necessary members to manage the entire gamut of drag-and-dropoperations Drag-and-drop is a complex topic; we’ll spend the entirety of chapters 13and 14 on this subject alone
drag-and-UTILITIES
The utilities section consists of cool utility classes that help you more easily perform some
of your routine tasks An example is Ext.util.Format, which allows you to format or form data easily Another neat utility is the CSS singleton, which lets you create, update,swap, and remove style sheets as well as request the browser to update its rule cache Now that you have a general understanding of the framework’s major areas offunctionality, let’s look at commonly used UI widgets that Ext JS has to offer
trans-1.3.1 Containers and layouts at a glance
Even though we’ll cover these topics in detail in chapter 3, let’s spend a little time
here talking about containers and layouts The terms container and layout are used
extensively throughout this book, and we want to make sure you have at least a basicunderstanding of them before we continue Afterward, we’ll begin our exploration ofvisual components of the UI library
CONTAINERS
Containers are widgets that can manage one or more child items A child item is erally any widget or component that’s managed by a container or parent; thus theparent-child paradigm You’ve already seen this in action in the API The tab panel is a
gen-Get your JSON on!
Even though JSON has been around for many years, if this is the first time you’veheard of it we encourage you to visit http://json.org, the go-to source for information
on this ubiquitous data exchange format If you’re interested in learning how to ment JSON in your server-side language of choice, there are a ton of JSON implemen-tations, most of which are documented and explained online We suggest searchingGoogle using a query like “PHP JSON.”
Trang 35imple-container that manages one or more child items, which can be accessed via tabs.Please remember this term, because you’ll use it a lot when you start to learn moreabout how to use the UI portion of the framework
LAYOUTS
Layouts are implemented by a container to visually organize the child items in thecontainer’s content body Ext JS has a whopping 33 layouts in the library! The goodnews is that you only have to learn 13 of them, which we’ll go into in great detail about
in chapter 5, where we show the ins and outs of each layout
Now that you have a high-level understanding of containers and layouts, let’s look atsome containers in action In figure 1.5 you see two subclasses of Container—Panel andWindow—each engaged in parent-child relationships, demonstrating the power of theContainer class and various layouts
The Panel (left) and Window (right) in figure 1.5 each manage two child items.Child Panel 1 of each parent container contains HTML The children with the title ChildPanel 2 manage one child panel each using AutoLayout, which is the default containerlayout This parent-child relationship is the crux of all the UI management of Ext JS andwill be reinforced and referenced repeatedly throughout this book
You learned that containers manage child items and use layouts to visually nize them Now that you have these important concepts down, we’ll see and discussother containers in action
orga-1.3.2 Other containers in action
You saw the Panel and Window subclasses used when you learned about Containers.Figure 1.6 shows some other commonly used subclasses of Container
In figure 1.6 you see the form panel, tab panel, window, toolbar, and field tainer widgets The form panel works with the Basic Form class to wrap fields and otherchild items with a form element All of these widgets are contained by an instance ofExt.window.Window
You’ll spend some time building a complex UI in chapter 6, where you’ll learnmore about form panels For now, let’s move on to see what data-presentation widgetsthe framework has to offer
Parent containers
Child containers
Child of child panel 2
Figure 1.5 Here you see two parent Containers, Panel (left) and Window (right),
managing child items, which include nested children.
Trang 36data stores, known as views Many of the views that you’ll deploy include the data view,
grid panel, and tree panel If your application requires charts, you’ll be pleased tolearn that all of the charts in the framework are also considered views and are bound
to data stores Figure 1.7 shows the Ext JS grid panel in action
The newly refactored GridPanel is a subclass of Panel and presents data in a like format, but its functionality extends far beyond that of a traditional table, offeringsortable, resizable, and movable column headers and selection models such as Row-SelectionModel and CellSelectionModel You can customize its look and feel andcouple it with a paging toolbar to allow large datasets to be segmented and displayed
table-in pages It contatable-ins many features and plug-table-ins, allowtable-ing you to do tasks such as edit
by row or cell, or lock a column The data view shown in figure 1.8 renders photos andother bits of data for various phones on the market
The DataView class consumes data from a store, paints it onscreen using a classknown as XTemplate, and provides a simple selection model The Ext JS XTemplate
is an HTML fragment-generation utility that allows you to create a template with
Window
Field container (field layout)
Tab panel (card layout)
Toolbar (HBox layout)
Figure 1.6 Commonly used subclasses of Container—FormPanel, TabPanel,
FieldContainer, and Toolbar—and the layouts used to compose this UI window We’ll
build this in chapter 6, when you learn about forms.
Trang 37placeholders for data elements, which can be filled in by individual records in a storeand stamped out on the DOM
The grid panel and data view are essential tools for painting data onscreen, but they
do have one major limitation: they can show only lists of records and can’t displayhierarchical data This is where the tree panel fills the gap
Gone is the list view widget!
If you’re coming from Ext JS 3, you may wonder where the list view widget is The ple answer is that the list view, providing faster table rendering in Ext JS 3.0, wasremoved from 4.0, in favor of refactoring the grid panel for much faster performance
sim-Figure 1.7 The grid panel as seen in the Buffered Grid example in the Ext JS SDK
Data view
Figure 1.8 The data view as demonstrated in the Ext JS SDK examples
Trang 38A tour of the Ext JS widgets
1.3.4 Make like a tree panel and leaf
The tree panel widget is an exception to the list of UI widgets that consume data inthat it doesn’t consume data from a data store Instead, it consumes hierarchical datavia the use of the TreeStore class Figure 1.9 shows an example of an Ext JS tree panelwidget Here, the tree panel is being used to display the parent-child data inside thedirectory of an installation of the framework
For Ext JS 4.0, it has been completely rebuilt and is now a close cousin to the gridpanel Figure 1.10 demonstrates the versatility of the new tree panel
Figure 1.9 An Ext JS tree, which is an example from the Ext JS SDK
Figure 1.10 A tree panel with columns
Trang 39You already saw text fields when we discussed containers Next, we’ll look at some ofthe other input fields that the framework has to offer.
1.3.5 Form input fields
Ext JS has a palette of eight input fields They range from simple text fields, asyou’ve already seen, to complex fields such as the ComboBox and the HTML Editor.Figure 1.11 shows the Ext JS form field widgets available out of the box
As you can see in figure 1.11, some of the form input fields look like stylized sions of their native HTML counterparts The similarities end there, though With theExt JS form fields, there’s much more than meets the eye
Each of the Ext JS fields (except for the HTML Editor) includes a suite of utilities toperform actions such as getting and setting values, marking the field as invalid, reset-ting, and performing validations against the field You can apply custom validation tothe field via regex or custom validation methods, giving you complete control over thedata being entered into the form The fields can validate data as it’s being entered,providing live feedback to the user
TEXTFIELD AND TEXTAREA
The TextField and TextArea classes can be considered extensions of their genericHTML counterparts that include extra features like validation The TextField class isthe base for many other complex widgets, such as the ComboBox, Number field, andTime field
Trang 40A tour of the Ext JS widgets
RADIO AND CHECKBOX
Like the text field, radio and checkbox fields are extensions of the out-of-the-boxHTML radio and checkbox, but they include all of the Ext JS element managementgoodness and have convenience classes to assist with the creation of checkbox andradio groups with automatic layout management Figure 1.12 shows a small sample
of how the Ext JS CheckboxGroup and RadioGroup classes can be configured withcomplex layouts
HTML EDITOR
The HTML Editor is WYSIWYG, like the text area on steroids The HTML Editor usesexisting browser HTML editing capabilities and can be considered somewhat of ablack sheep when it comes to fields There’s much more to discuss about this field,which we’re going to save for chapter 6 But for now, let’s circle back to ComboBox andits subclass, TimeField
TRIGGERFIELD FAMILY OF FIELDS
The TriggerField class is the base class responsible for rendering a button to theright of a text field Its subclasses are broken up into two groups, pickers and spinners.Included in the list of pickers are the ComboBox and the date field The spinnersinclude the spinner and number fields
The ComboBox is easily the most complex and configurable form input field Itcan mimic traditional option drop-down boxes or can be configured to use remote
datasets via the data store It can be configured to autocomplete text (known as
type-ahead) entered by the user and to perform remote or local filtering of data It can also
be configured to use your own instance of an Ext JS XTemplate to display a custom list
in the drop-down area, known as the bound list Figure 1.13 shows an example of a
cus-tom ComboBox in action, being used to search the Ext JS forums
The ComboBox here shows information like the post title, date, and author, and asnippet of the post in the list box Because some of the dataset ranges are so large, it’sconfigured to use a paging toolbar, allowing users to page through the resulting data
Figure 1.12 An example of the Checkbox and RadioGroup convenience
classes in action with automatic layouts