Chapter 14. The Power of Ext JS: What Else Can You Do?

Throughout this book, we've gone over some of the core components of Ext JS: Windows and Dialogs, Grids, Trees, Data Stores, and more. This is some of the flashiest, coolest, and most consistent stuff on the Web today, for taking a drab old HTML display and giving it the sizzle and pop such a dynamic development platform deserves. But we've still only scratched the surface of what's available within the complete Ext JS library.

So much to work with

The Ext JS site (http://www.extjs.com) provides a wealth of information for those learning to develop with Ext JS. A quick view of the Samples and Demos area of this site will show us quite a bit of what we've covered in this book, but a thorough examination of the source code will show us some things that we may not immediately have known were available. These are the pieces that aren't necessarily apparent, such as a panel or a grid, but these little things ultimately hold it all together and truly allow us to create robust applications.

Form widgets

What's a widget? Well, a widget is a tiny piece or component of functionality, say (for instance) a slider or a progress bar. Most applications are made up of forms, so it's no accident that Ext JS includes some form widgets that we can't get with straight HTML. TextFields and Checkboxes and Radio buttons are standard fare, but Ext JS sweetens the pot by going to the next level, providing us with components that we're used to seeing in most desktop applications.

DateField

The DateField is a perfect example. Handling dates within most HTML forms can be a chore, but Ext JS provides a very basic component for handling dates:

Example 1:ch14ex1.js

Ext.onReady(function(){
var formPanel = new Ext.form.FormPanel({
title:'DateField Example',
applyTo:'chap14_ex01',
layout:'form',
labelAlign:'top',
width:210,
autoHeight:true,
frame:true,
items:[{
xtype:'datefield',
fieldLabel:'Date of Birth',
name:'dob',
width:190,
allowBlank:false
}]
});
});

What we have here is a basic FormPanel layout, that puts our DateField into proper context and allow for certain necessary attributes (like putting our label above the field). Within the layout we have a single DateField component. On initial load, it looks like a basic TextField, with the exception of the trigger to the right. Clicking the trigger shows the beauty of Ext JS's consistent component "look-and-feel", displaying an attractive calendar layout for the selection of a date. You can select a day, move from month-to-month, or even click on the month itself to choose a different month and year.

DateField

Apart from its rich display, the DateField also provides a rich set of attributes for specialized customization, including the ability to determine different accepted date formats, and the ability to disable entire blocks of days. The component will also automatically validate manually-entered data.

TimeField

Dealing with time can be more difficult than dealing with dates, but Ext JS, again, provides a component to assist us. The TimeField is, ultimately, a basic ComboBox that will automatically show a set of time, in increments that we want, for quick selection:

Example 2:ch14ex2.js

Ext.onReady(function(){
var formPanel = new Ext.form.FormPanel({
title:'DateField Example',
applyTo:'chap14_ex02',
layout:'form',
labelAlign:'top',
width:210,
autoHeight:true,
frame:true,
items:[{
xtype:'timefield',
fieldLabel:'Time',
minValue: '9:00 AM',
maxValue: '6:00 PM',
increment: 30
}]
});
});

As in our last example, this simple FormLayout contains one item, in this case the TimeField. Click on the trigger, and we get our options, defined by our code as times between 9 AM and 6 PM in increments of 30 minutes. Other configuration options allow you to define multiple accepted time formats, and also implement custom validation. Basic validation is provided by default.

TimeFieldform widgetsDateField

NumberField

The NumberField doesn't look very special—it's just a basic 'text' field. What makes it special is how it allows us to 'dummy-proof' our Ext JS applications. Client-side data validation is essential for ensuring data integrity prior to sending values to the server, allowing us to prevent errors from our remote procedure calls. Components such as this one simplify that process for us. The NumberField provides automatic keystroke filtering and validation to allow the entry of only numeric data, allowing us to specify whether it can take negative numbers or float values, and even specify how many decimal places are accepted.

CheckboxGroups and RadioGroups

Ext JS 2.2 brought two new form controls: the CheckboxGroup and the RadioGroup. These controls allow us to 'group' sets of checkbox or radio buttons, providing them with custom formatting and special, group-level validation capabilities. For example, say we have a form with two checkboxes for the users to select their gender. By placing these within a CheckboxGroup, we can apply our validation to the group so that at least one option is selected when the form is submitted. We can apply many more complex validation rules as well, depending upon the scenario. See the Ext JS API for more details.

HtmlEditor

Ext JS includes a nice, limited, WYSIWYG HtmlEditor, to drop right into your forms:

Example 3:chapter14_03.js

Ext.onReady(function(){
var formPanel = new Ext.form.FormPanel({
title:'HtmlEditor Example',
applyTo:'chap14_ex03',
layout:'form',
labelAlign:'top',
width:600,
autoHeight:true,
frame:true,
items:[{
xtype:'htmleditor',
id:'bio',
fieldLabel:'Blog Entry',
height:200,
anchor:'98%'
}]
});
});

Here we dropped the HtmlEditor into our FormLayout for a quick demonstration. The HtmlEditor is applied to a basic text area, in much the same way as other WYSIWYG editors, say FCKEditor or TinyMCE. We have the ability to enable or disable the various menu buttons related to formatting, as well as call various methods (like those to get or set the text of the editor, its position, and so on), or apply event listeners, just like the other components of Ext JS.

HtmlEditor

We get the same, consistent Ext JS look and feel, while giving our users the ability to format their own content directly from within our applications. In this image, note that the HtmlEditor uses Ext JS's built in ColorPalette component for selecting colors.

Data formatting

We all know that we don't always receive data in the format in which we want it to be displayed. Ext JS provides many different components specifically for address such issues. First among these is the Format object in the Ext.util package, which gives us a wide variety of functions for everything from creating the US currency format for a number to methods for stripping scripts and HTML from strings. The Ext JS library also extends several native JavaScript objects and provides us with additional methods for manipulating them. Specifically, the String, Number, and Date objects have all been extended. You can now strip off unnecessary whitespace, constrain numbers to a minimum and maximum value, and even create Date objects from a variety of format options.

Basic string formatting

The String object has been extended to provide several formatting options, including the format() method. This simple method allows you to return a formatted string of text, with the first parameter being the string to return, and all other parameters (as many as you like) being bound to pieces of the string, using a basic form of binding expression, whereby curly braces surround a variable reference. Typical binding expressions, used by Ext JS, would contain a dot-notated variable reference surrounded by curly braces (that is, {this.firstName}), but this instance will bind values to the arguments that will follow using their array order:

Example 4:chapter14_04.js

Ext.onReady(function(){
var cls = "Band";
var member = {
firstName: 'Eric',
lastName: 'Clapton',
position: 'Lead Guitarist'
};
var pnl = new Ext.Panel({
applyTo: 'chap14_ex04',
width: 200,
height: 100,
bodyStyle: 'padding:5px',
title: 'Band Member',
html: String.format('<div class='{0}'>{2}, {1}: {3}</div>', cls, member.firstName, member.lastName, member.position)
});
});

This small block of code displays a simple Panel element, which calls the formatting function to build the HTML of the Panel. The format() method's arguments are applied to different parts of the string that we are building.

Basic string formattingdata, formattingabout

Formatting dates

The Date object has also been extended to provide additional formatting and parsing capabilities. The API provides a complete listing of the date part identifiers that can be used when parsing a string into a Date object, or when outputting a Date object in the desired format:

Example 5:chapter14_05.js

Ext.onReady(function(){
var cls = "Band";
var member = {
firstName: 'Eric',
lastName: 'Clapton',
position: 'Lead Guitarist',
birthDate: new Date('03/30/1945')
};
var pnl = new Ext.Panel({
applyTo: 'chap14_ex05',
width: 200,
height: 100,
bodyStyle: 'padding:5px',
title: 'Band Member',
html: String.format('<div class='{0}'>{2}, {1}: {3}<br />DOB: {4}</div>', cls, member.firstName, member.lastName, member.position, member.birthDate.format('F j, Y'))
});
});

We've extended our previous example to add Eric's birthday. We've created a new Date object, as part of the Member object, and then used the format() method of the Date object to format our date for display.

Formatting dates

Other formatting

The Ext.util package provides many different classes and methods for formatting various types of data, including many for working with strings, dates, and numbers. A good example is the usMoney() method:

var annualSalary = 123456.345;
Ext.util.Format.usMoney(annualSalary);

This will return a pre-formatted US currency string of $123,456.35. This can come in very handy when working with e-commerce applications. This is only one of the many methods within the classes of the Ext.util package.

Note

Author's note

Currently, as far as working with currency is concerned there is only a usMoney() method in the Format class. But, with Ext JS's extensible architecture, it would be possible to create methods for formatting other foreign currencies. A quick search of the Ext JS forums will pull up several posts on creating formatting methods for other currency types.

Another common function is the ability to strip HTML from a string. Say we have a simple comment form on our page, and want to ensure that the user doesn't include any HTML in the input, so that our data isn't polluted before going to the server. Ext JS includes a simple method for stripping out HTML from any string:

var firstName = '<b>jimi</b>';
var adj = Ext.util.Format.stripTags(firstName);

We may also want to make sure that a particular input, say a name, is capitalized before we pass it back to the server:

var adj2 = Ext.util.Format.capitalize(adj);

We may also want to apply a default value to a variable in case one does not exist already:

var adj3 = Ext.util.Format.defaultValue(favoriteBlog, 'Cutter's Crossing');

These are just a few of the many formatting methods that are available within the Ext JS library. A thorough review of the API will provide you with a full understanding of everything that is available.

Managing application state

Core to any application (especially an event-driven application) is maintaining and controlling 'state'. This can encompass many different things, from keeping user preferences on grid sorting, to managing multiple Windows or layout areas on the screen, and even being able to use the Back button in the browser and have it change your application without reloading the wrong page. Luckily, Ext JS provides several Manager objects for handling many of these exact scenarios.

Basic 'state'

The Ext.state.Manager class is automatically checked, and utilized, by every state-aware component within Ext JS. With one simple line of code we can set this manager in place, and with little or no additional work, our application's view state is automatically registered.

To put this in perspective, suppose that we have a rather large application, spanning many different HTML documents. Ext JS plays a part in the application, because we've implemented a data grid for displaying users. While we work on our grid, it may be necessary to change the sort order from the default LastName column to an unlikely column, say the UserName column. Now let's say we had to go into an inventory editor for a moment. If we use the Manager, when we return to the user editor our grid will automatically come up sorted again by Username, as that was the last state change that we made:

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

This line creates our state Manager, setting the provider to a CookieProvider. What this means is that the application state is saved to a value within a cookie on the client machine, which in turn is read to re-enable the state upon returning to a state-aware component.

Note

Side Note

The CookieProvider also provides a simple API for the general management of client-side cookies for our sites, and can be used as a standalone class for referencing and manipulating cookie objects.

How do I get that window?

Many Ext JS applications will be confined to a single HTML page, and might commonly come down to a collection of Ext JS Window objects on the screen. But what happens if a user is in one window, and we want to show them another window that is already open, without closing the one they've been working on? By default, all Ext JS windows are created, and registered, within the global WindowGroup. We can easily control the state of these windows by using the WindowMgr class. This manager class allows us to grab any window of a WindowGroup, and bring it to the front, send it to the back, or even hide all of the windows in the group.

Using the back button in Ext JS applications

One common problem among Rich Internet Applications is handling the Back button of the browser. Say we have a large Ext JS based application with Tabs, Grids, and Accordions. A user, navigating our application by using these components, might hit their Back button to go back to their last action, or screen, or panel. This is expected behavior in most Internet applications, because most Internet applications go from one HTML page to another.

But most Rich Internet Applications, like those built with Ext JS, are usually a collection of different states within the same HTML page, and the Back button would typically take a user out of our application and back to the last viewed HTML page. Thankfully, Ext JS 2.2 (the latest library update, as of this writing) introduced the History class, giving us the ability to control how the browser history is used, and how the browser's Back button would be handled within our applications.

Note

Manage this

There are several other Manager classes within Ext JS. The StoreMgr provides easy access to our various data Store objects. The ComponentMgr allows us to quickly retrieve specific components to act upon. The EventMgr allows us to control events within Ext JS objects. A good review of the Ext JS API will give us more information on these Manager objects and their many uses.

Accessing the DOM

Custom library adapters allow for the use of Ext JS with other libraries, say JQuery or Prototype. But Ext JS provides its own internal libraries for DOM manipulation as well.

Finding DOM elements

The first task when manipulating the DOM(Document Object Model) is to find what we're looking for. The DomQuery class provides us with several methods for this purpose, including returning entire groups of DOM nodes that meet specific criteria, or selecting a single node by its selector. We can even start the search from a specific node in the page. There are several different selector types that can be used when searching for a specific element:

  • base Element Selectors

  • Attribute Selectors

  • Pseudo Classes

  • CSS Value Selectors

What's more, we can chain together a series of selectors to find the exact element we're searching for:

var myEl = Ext.DomQuery.selectNode ('a.iconLnk[@href*="cutterscrossing"]:first');

This will return the first anchor element with a class name of iconLnk that contains 'cutterscrossing' within its href attribute:

  • a: Is an anchor element

  • .selectNode: Is a class of selectNode

  • [@href *= "cutterscrossing"]: Is an href attribute containing 'cutterscrossing' somewhere within its value

  • :first: Is only the first element matching the criteria

Manipulating the DOM

The DomHelper class allows us to manipulate the DOM of the rendered page on the fly. Whether we want to add a new element below a collection of others, remove a specific element, or even overwrite the body content of an element, the DomHelper class contains the methods that can accomplish the task:

Ext.DomHelper.insertAfter(ourGrid, newForm);

This line will place the newForm object directly after ourGrid in the current page's DOM. You could just as easily use insertBefore() to place the form before the grid. You could even use insertHtml() to insert a block of HTML into the DOM with a particular relation to a specific DOM element. A thorough review of the API will give you a complete view of the power of the DomHelper class.

Working with styles

The DomHelper class also provides a simple method for setting the style of an individual element, through the use of the applyStyles() method. But sometimes we may need to change the style sheet of our entire document. For this, Ext JS has the Ext.util.CSS class, which allows us to create a new stylesheet that will automatically be appended to the Head of our document, remove entire stylesheets, or swap one stylesheet for another. We can even act upon their entire set of rules:

Ext.util.CSS.swapStyleSheet('defaultDisplay','print.css');

This little script will swap out the current stylesheet, which is identified by the link tag's id attribute, and replace it with the print.css stylesheet.

Ext JS for the desktop: Adobe AIR

One of the great things about being a web application developer is that we have the opportunity to write truly cross-platform applications. The traditional model for this has always been writing browser-based applications that work primarily under a client/server paradigm, with the browser as the client and a web application server as the server.

But desktop applications have a lot of their own benefits, including access to their own local file systems (something you cannot do with web-based applications, because of security concerns). The biggest issue with building desktop applications is writing them for all of Windows, Unix/Linux, and the Mac. None of these systems share common display libraries or file access systems, so writing a cross-platform application would require writing separate versions of the code to accommodate each system. There are languages that provide cross-platform virtual machines, which give this kind of access to the system resources, but they require learning languages that may be of outside the average web developer's toolbox.

Adobe came up with an interesting idea. How could they let people develop cross-platform applications using web-based technologies such as HTML, JavaScript, AJAX, and Flash?

With their purchase of Macromedia, Adobe gained the rights to the Flash player and the Flash application platform. The Flash player is distributed on 97% of the user desktops as a plug-in for every major browser. They also gained access to a new technology called Flex, which is a framework and compiler that allows developers (rather than designers) to script Flash based applications.

But, part of what they truly gained was an understanding of how to create a cross-platform application delivery engine. So, they built upon their new-found knowledge, and set out to create the Adobe Integrated Runtime, better known as AIR. AIR is a desktop engine for rendering content written in HTML, JavaScript, and/or Flash (and more), which allows local access to the client system's resources, regardless of the operating system. Built upon the open source WebKit platform, which is the same platform used by Apple in their Safari web browser, AIR has access to the local file system and storage, while maintaining Internet awareness, thereby creating a bridge between offline process and online content. AIR even provides access to local databases created with SQLLite. SQLLite is a server-less library for delivering databases, with its own transactional SQL database, engine that can be directly embedded into an application.

Adobe and Ext JS already have a great relationship, because Adobe contracted Ext JS so that it could use the Ext JS component library as the foundation of the AJAX-based components generated by ColdFusion Markup Language, which is processed on Adobe's popular ColdFusion application server. And Considering the cross-platform nature of AIR, it was befitting that some of the first HTML/JavaScript sample applications were written in another cross-platform library, Ext JS. The tasks sample application is included with the Ext JS download, and is an excellent primer on how to write HTML and JavaScript applications for AIR.

Ext JS 2.1 was released on the same day that Adobe AIR was officially released, and included an entire package of components dedicated to developing Ext JS-based AIR applications. The classes of the Ext.air package interact with AIR's own classes for interacting with the runtime and the desktop. Aptana, a popular JavaScript editor and Eclipse plugin, added support for creating AIR applications directly as projects from within its IDE (Aptana already supported Ext JS development), with simple wizards to help get you started, as well as for packaging completed AIR applications.

To make life easier, the base Ext JS class provides an isAir Boolean property that can be used to conditionally run applications concurrently on the web and within an AIR application, utilizing the same codebase. The Ext.air package includes special packages for managing application state, including the NativeWindowGroup and FileProvider classes (AIR's answer to the WindowGroup and CookieProvider classes). There are even classes for controlling sound and system menus.

Note

More information:

For more information on developing Adobe AIR applications, visit the AIR and AJAX Developer Center (http://www.adobe.com/devnet/air/ajax/). For details look at AIR/Ext JS integration, study the 'tasks' sample application, included in the complete Ext JS download. There's also the Ext.air for Adobe AIR topic within the Ext JS Forums.

Ext JS community extensions

Chapter 13 of this book discussed how developers can write their own custom extensions to Ext JS. Being an open source project, the Ext JS community is very active in contributing new components to extend existing functionality, and sometimes these components even go on to become a part of the framework.

Many custom extensions are found directly in the forums area of the Ext JS website, as posts from members who have come up with solutions to a problem they had identified. There is, however, a section of the Learning Center area of the site that is dedicated to showcasing custom extensions. Here are a few fan favorites:

DatePickerPlus

Building on the DateField class, the DatePickerPlus provides multi-calendar displays, allowing a user to select a range of dates. There are multiple configuration options available, and the level of control available to the developer is very comprehensive.

DatePickerPlus

PowerWizard

The PowerWizard class allows us to create powerful, multi-step 'wizard-like' processes, with field (and multi-field) validation and decision trees, as well as data persistence between frames.

PowerWizard

TinyMCE

Yes, for those times when the HtmlEditor just isn't enough, someone wrote a custom extension to wrap the TinyMCE WYSIWYG editor into the Ext JS applications.

TinyMCE

SwfUploadPanel

How many times would it have been nice to be able to upload more than one file at a time through our web application interface? Someone converted the popular SwfUpload project into a custom Ext JS component, allowing multi-file uploads from within our application.

SwfUploadPanel

ColorPicker

The built-in ColorPalette component can seem rather limiting, only showing a few of the colors available for web display. For this reason, there is the ColorPicker giving the user the option of selecting any color they wish.

ColorPicker

These are just a few of the outstanding community contributions to the library. There are many more available through the Community Extensions section of the Learning Center area of the Ext JS website, as well as throughout the Forums (Checkout the Ext: User Extensions and Plugins topic for more).

Additional resources

Knowing where to find good information is the biggest trick to learning anything new. Although this book is a good resource, there is a wealth of information available on the Internet, especially on the Ext JS site (http://www.extjs.com).

Samples and demos

The Samples and Demos area of the Ext JS site (http://extjs.com/deploy/dev/examples/samples.html) will likely be the first real exposure that anyone has to the power of the Ext JS library. These small samples are broken down into various categories, providing us with solid examples of how to use many of the components of Ext JS. With easily-accessible source code, we can see exactly what it takes to write this type of functionality for our own applications.

Ext JS API

The Ext JS interactive API (http://extjs.com/deploy/dev/docs/) is an outstanding resource, giving us access to the underlying properties, methods, and events that are available within each class of Ext JS. Peppered throughout are additional code samples to illustrate their use. The Ext JS team even provides a desktop AIR version of this API browser, so that we can have it available offline.

Note

Side note:

The Ext JS team also supports the older 1.1 framework, which is what runs the underlying AJAX components of the Adobe ColdFusion 8 server. The samples and demos for the 1.1 framework are actually included in the 1.1 API browser (http://extjs.com/deploy/ ext-1.1.1/docs/), which is available through the Learning Center area of the website (http://extjs.com/learn/).

Ext JS forums

The Forums for Ext JS (http://extjs.com/forum/) show what an active community there is, developing the Ext JS library. With over 40,000 threads and more than 200,000 posts, this is the place to ask questions. Topics range from the very easy to the ultra-advanced, and members of the core Ext JS development team are frequent contributors.

Step-by-step tutorials

Step-by-Step Tutorials(http://extjs.com/learn/Tutorials) can be found within the Learning Center, with content ranging from simple component usage to advanced project development. Some of these tutorials come directly from the Ext JS development team, but many are contributed by members of the Ext JS community.

Community manual

One can also find the Ext JS Community Manual within the Learning Center. This wiki-style development manual is maintained by the Ext JS community itself, and contains topics relating to most of the aspects of Ext JS development.

Spket IDE

We can find resources for Ext JS all over the Internet. One good example is from Spket Studios (http://www.spket.com/), makers of the Spket IDE. This free IDE comes as a plug-in for the Eclipse development platform. With a few simple steps, Spket can provide complete code introspection for our Ext JS classes and extensions, as well as in-depth code assistance. It even has a built-in theme builder to automatically create new skins for your components.

Aptana Studio

Aptana Studio is quickly becoming a major contender in the web-based IDE market. Even the free version provides code introspection and assistance with multiple JavaScript libraries, built-in wizards for creating Adobe AIR applications, built-in debugging tools, and much more.

Google

Yes, Google (or any other search engine) is a fantastic resource, because there are thousands of articles, tutorials, and blog posts available. A quick search on "Ext JS" brings up over a million possible matches, and that's growing every day.

Summary

In this chapter we've discussed some of the lesser known pieces of the Ext JS library. We briefly covered some of the form components not found in traditional HTML, such as the DateField and the HtmlEditor. We also learned about the various classes available for formatting data for the desired output, as well as those classes needed for managing application state and manipulating the Document Object Model. We also briefly talked about creating Ext JS desktop applications with Adobe AIR.

Finally, we also talked about the various resources that are out there for continuing to learn about Ext JS development. We talked about the community extensions, the brilliant samples, and API browser, as well as the forums, tutorials, and the community manual. We even touched on some IDE's for doing Ext JS development.

Where do we go from here?

It is our hope that, with this brief introduction to the Ext JS JavaScript component library and framework, we've given our readers a good foundation upon which some truly amazing things can be built some truly amazing things. Ext JS provides such an immense wealth of user interactivity within web applications, possibly to a degree never achieved before. With its deep, consistent, and rich component set, its full-featured and intuitive API, and its constant development and growth, Ext JS has the potential to truly springboard web (and even desktop) applications beyond the traditional paradigms, by providing users with an experience well beyond the web applications of the past.

Our imagination is the only limit to what we can hope to have in the future.

Charles F. Kettering

US electrical engineer and inventor (1876 - 1958)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.181.89