Archive for the ‘ExtJs’ Category

Web Application Architecture with ExtJS

Wednesday, June 23rd, 2010

I’ve spoken at great length about the need for developers to have an organized User Interface, and I frequently see questions posted to the ExtJS Sencha message boards asking about “Best Practices” for creating a web application with the ExtJS framework.

As I recently started a new project using ExtJS, I thought I would share some of my own advice on the subject.

Folder Structure

Architects build things… and as software architects, it’s our job to build an organized folder structure as the solid foundation for our web application. Organization is the key here; we don’t want to be searching through our IDE for hours trying to find something. To accomplish this task, we will setup a UI based on “tiers” (think of an N-tier application).

A habit I’ve developed over the years is to create a root-level folder named with an underscore as the first character (/_app/) which contains important UI application files. The underscore is important for two reasons:

  1. it visually stands out, and
  2. it will be listed at the top when sorted alphabetically

For argument’s sake, we will create a folder structure for our application which looks like the following:

Web Application Architecture with ExtJS: Folder Structure

In this way, we keep all of our UI application code separated from other web entities like HTML and image files. (I consider JavaScript and CSS to be “UI application code”, which I define as logic or presentation within the UI. HTML and other file types are generally more structural and are dependent on JS or CSS. Server-side files often contain logic, but fall into a different tier of the application at large.)

If necessary, the folder structure can be much more robust – it completely depends on how your application works. For example, a project running ASP.NET MVC will have root-level folders for Models, Controllers and Views which contain code specific to their tier’s functionality.

ExtJS Framework

The first thing any application using ExtJS will need is the framework itself (duh!). Copy the ExtJS files to /_app/ext-3.2.1/ Name the folder to match whatever version you’re running – this makes future upgrades a breeze.

Assuming that you’re not using ExtJS in conjunction with another framework (like jQuery), your application simply needs to include three files:

  • ext-all.css
  • ext-base.js
  • ext-all.js (or ext-all-debug.js)

I always like to include the CSS file before the JS files, but that’s just my preference. ext-base.js must be included before ext-all.js – read your INCLUDE_ORDER.txt file!

    <!-- ExtJS Framework -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-3.2.1/resources/css/ext-all.css" />
    <script type="text/javascript" src="/_app/ext-3.2.1/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="/_app/ext-3.2.1/ext-all.js"></script>

Themes

If you have any custom ExtJS themes that you plan on using for your application, this would be the appropriate time to add them.

Place these files in the /_app/ext-themes/ folder. We specifically separate these files from /_app/ext-3.2.1/ to simplify the upgrade process should you migrate to a newer version of ExtJS in the future.

    <!-- ExtJS Themes -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-themes/css/xtheme-XYZ.css" />

Overrides

Next, you should create CSS and JS files to place any overrides which you’ll need. These overrides are generally bug fixes – not customizations. The point of these files is to have a central place for fixing oddities in the ExtJS framework which may be fixed in a future release.

Here’s what I call these files:

  • Ext.Overrides.css
  • Ext.Overrides.js
    <!-- ExtJS Overrides -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-overrides/Ext.Overrides.css" />
    <script type="text/javascript" src="/_app/ext-overrides/Ext.Overrides.js"></script>

At this point in our application (the beginning), we probably won’t have any overrides since we haven’t started writing any code. One exception is the global variable BLANK_IMAGE_URL value, which needs to point to our local application (not the remote ExtJS server, which is by default).

In our Ext.Overrides.js file, simply add the following:

    Ext.BLANK_IMAGE_URL = '/_app/ext-3.2.1/resources/images/default/s.gif';

UX Classes

Last but not least, we can now include any ExtJS user extensions (UX) that we need for our application.

    <!-- ExtJS UX -->
    <script type="text/javascript" src="/_app/ext-ux/Ext.ux.XYZ.js"></script>

Application Code

The first thing we should create at this point is our application CSS files (placed in /_app/css/ ). These styles may or may not have anything to do with our JS classes, but we obviously need to include them. I suggest including these styles now (as opposed-to before the ExtJS styles) because we don’t want ExtJS to overwrite any of our custom styles. (Browsers apply styles based on the most recently included definition.)

Next it’s time to add our custom application classes (placed in /_app/js/ ). Although I won’t go into any specific details about how to write your classes, I highly suggest reading the posts by Ed Spencer and Jay Garcia (see below under Resources) which contain excellent tutorials.

Namespace

I usually start by creating a namespace file which asks ExtJS to creates all of my application namespaces before I load my JavaScript classes. This isn’t necessary, but I’ve found that creating the namespaces early often prevents errors due to classes being included in the “wrong order”. It can also save code, as none of your classes need to explicitly create their own namespace.

I call this file _Namespace.js – using the same naming convention as before (starting with an underscore) to draw attention to its importance. It’s contents include only a handful of lines (depending on how large your application is). This file should only contain namespace definitions.

    Ext.namespace(
        'NS1',
        'NS2',
        'NS3'
    );

Also, if you’re going to use this idea, be sure to include _Namespace.js before any of your other application files!

JS Classes

Lastly, we can include all of our application’s JavaScript classes in the HTML header.

    <!-- Application Files -->
    <link rel="stylesheet" type="text/css" href="/_app/css/styles.css" />
    <script type="text/javascript" src="/_app/js/_Namespace.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass1.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass2.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass3.js"></script>

Put It All Together

    <!-- ExtJS Framework -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-3.2.1/resources/css/ext-all.css" />
    <script type="text/javascript" src="/_app/ext-3.2.1/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="/_app/ext-3.2.1/ext-all.js"></script>

    <!-- ExtJS Themes -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-themes/css/xtheme-XYZ.css" />

    <!-- ExtJS Overrides -->
    <link rel="stylesheet" type="text/css" href="/_app/ext-overrides/Ext.Overrides.css" />
    <script type="text/javascript" src="/_app/ext-overrides/Ext.Overrides.js"></script>

    <!-- ExtJS UX -->
    <script type="text/javascript" src="/_app/ext-ux/Ext.ux.XYZ.js"></script>

    <!-- Application Files -->
    <link rel="stylesheet" type="text/css" href="/_app/css/styles.css" />
    <script type="text/javascript" src="/_app/js/_Namespace.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass1.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass2.js"></script>
    <script type="text/javascript" src="/_app/js/MyClass3.js"></script>

Optimization

Larger applications may have hundreds of JavaScript files containing custom classes, methods, etc. Simply including each file in the HTML header will result in potentially long page load times – and this is far from ideal.

Many web servers compress JS files for you, and you always have the option of minifying your code – but loading hundreds of compressed and minified files still takes time and bandwidth.

One option is to combine/compress all of your classes into a single file – exactly as ExtJS has done with their ext-all.js file. This is a great solution – but it’s a manual process, one which can be tedious and is prone to user-error.

A far better solution is to automate this process – and if you’re using Visual Studio (like me), Dave Ward has a great post on setting that up.

Lastly, tools such as YSlow and Google Page Speed will suggest adding your JavaScript files to the bottom of the page. This may be advantageous; however, if your application makes use of the ExtJS Viewport or the famous Ext Desktop example, it probably won’t do much good as the UI is completely dependent on the JS framework.

Your Thoughts

Do you have any thoughts on what I’ve described above? Are you doing something that I missed?

I look forward to seeing your comments!

Resources

ExtJS, Flickr and Wordpress

Tuesday, April 13th, 2010

I recently built a website for my sister (Jennifer Kay) to showcase her professional work as a reporter for the Associated Press. The design is simple – but I thought I might share something cool with everyone.

For starters, byJenniferKay.com is built on WordPress so that my sister can make content edits quickly and easily without having to look at HTML code.

I also chose to use ExtCore to display a slideshow of my sister’s photography. The implementation of the slideshow is hardly anything worth noting as it’s basically the standard ExtJS Carousel example.

But here’s the cool part: my sister can edit the slideshow from her Flickr account without touching a single line of HTML or JavaScript!

Now some of you may be asking yourselves, “How is this possible?” I promise you it’s far easier than you might think.

I stumbled across the flickrRSS plugin for WordPress awhile back and noticed it would be perfect for something like this. Using the Flickr API, the plugin simply fetches recent images from a Flickr account (or images with a specific tag) and pastes them into your WordPress blog. Not exactly rocket science; in fact, it’s laughably simple.

Here’s how it works:

  1. Install WordPress (duh!)
  2. Download and install the flickrRSS plugin
  3. Edit your WordPress template to include this code where the slideshow should appear:
    
        <div id="slideshow">
            <?php get_flickrRSS(); ?>
        </div>
    
  4. Edit the settings for flickrRSS so that it outputs the images with this code:
    
    <img src="%image_medium%" alt="%title%" />
    
  5. Download ExtCore and the JS/CSS files for Ext.ux.Carousel (total of 3 files)
  6. FTP the ExtJS files to your server and include them in your template
  7. Add the following JavaScript code to your template:
    
    <script type="text/javascript">
        Ext.onReady(function() {
            new Ext.ux.Carousel('slideshow', {
                itemSelector: 'img',
                interval: 5,
                autoPlay: true,
                showPlayButton: true,
                pauseOnNavigate: true,
                freezeOnHover: false,
                transitionType: 'fade',
                navigationOnHover: false
            });
        });
    </script>
    

Your slideshow should now appear and work without any problems! Best of all, changing the photos is easy – simply login to your Flickr account and add photos.

Ext Scheduler

Monday, February 8th, 2010

A few weeks ago, Mats Bryntse (mankz on the ExtJS forums) asked me if I would be interested in taking a look under the hood of his Ext Scheduler application. There has been a great deal of buzz in the ExtJS community over his tool, so I jumped at the chance to peek into his source code. We’ve never actually met in person, but Mats seems like a good guy and he has a lot of good insight on the ExtJS forums. Apparently Mankz is also a DJ; I did not know that!

Disclaimer: Mats granted me a free license to use the tool in exchange for my review.

After unzipping the source code, I poked through a few of the examples. At first glance I was very impressed! The download came packaged with six demos, each of which utilizes different ExtJS features and gathers data via different sources (eBay, Google Calendar, among others). My only immediate complaint was that the API documentation wasn’t included in the ZIP file. It is however freely available on the Ext Scheduler website here.

Let’s Build Something Fun!

Rather than just saying what the Ext Scheduler does… let’s build something! Since Ext Scheduler’s website already has a handful of examples, I’d like to try building something new — let’s use the Twitter API and map when our tweets are posted.

A quick note: I didn’t realize something important until I was almost done with this application – the Twitter API doesn’t allow you to grab tweets based on a given time frame. You’re only allowed to grab the last X tweets… which I think is pretty lame. Had I know that before starting this application, I would have chosen a better example. *Facepalm!*

My journey through the Ext Scheduler started with a quick look through the API docs. The basis for the entire application is the Sch.SchedulerPanel() class, which is an extension of the Ext.grid.GridPanel(). If you read the API docs for this class, you’ll learn that it depends on two data stores: the first (“Store”) defines the various categories/rows for your application, while the other (“EventStore”) defines the events displayed on our schedule.

For my sample application, the “Store” will consist of a single Twitter user and the “EventStore” will be filled with this user’s 50 most recent Tweets. Thus, my application only has one row on the grid (boring, I know). I chose to display my grid as a 24 hour day so we can see our user’s Twitter activity over the course of a single day. Toolbar buttons allow us to move forward/backward by day. (Since the Twitter API doesn’t take start/end date parameters, this functionality is somewhat pointless.)

Take a moment now and try my sample application. We’ll explore it in more detail below, but see the source code here.

Learning Curve

My only real complaint with the Ext Scheduler code is the fact that there’s a slight learning curve. The examples provided in my ZIP folder are great, but there’s so much going on in each demo that it’s hard to figure out the basics. It took me the better part of a day to get my application working, so be prepared for a little bit of frustration.

Don’t get me wrong – this is an awesome tool, and I had the same complaints about ExtJS when I first started too. As such, I’m hoping this review can be a step-by-step demonstration on how to get started.

Step One: Define Your Categories

The “CategoryStore” is used for our left-hand grid labels – the entities to which the events are associated. In some of the other Ext Scheduler examples, the “Categories” were often people; the “Events” were often meetings or other appointments.

I started my application by prompting the user for their Twitter username. If you open my source file, you’ll see that I take the user’s input and insert it as a new data record into my TwitterApp.Scheduler.categoryStore (an Ext.data.JsonStore()). That was easy!

Next, I call the init() method on my TwitterApp.Scheduler object (a generic literal), which calls a series of other methods. In essence, here’s what they do:

  • Set this.start and this.end (values needed to properly display data in our schedule)
  • Create and load our “EventStore” (we’ll come back to this in a moment)
  • Create the scheduler grid and render it to the UI

Step Two: Define Your Events

As I just mentioned, we need to create and load the event data to display on our schedule. See the following code:

Ext Scheduler Demo

Our “EventStore” is another simple Ext.data.JsonStore() object; however, I’m pulling the data for this store from the Twitter API (based on the supplied username).

Take note of the “start” and “end” base parameters on this store. Although Twitter doesn’t really need them (which is why this example kinda sucks), the Ext Scheduler classes do! If you don’t add these parameters you’ll get an error!

When this store finishes loading (see my LOAD event), I manually set the “EndDate” property for each record because Ext Scheduler needs this information.

Step Three: Create the UI

Once we have our categories and events defined, we have the data we need to display the Ext Scheduler UI.

The Sch.SchedulerPanel() class is an extension of the ExtJS GridPanel(). The only things we really need to be aware of are the autoViews property and the eventTemplate since they’re the two things which really affect the appearance of our tool.

For the autoViews, you have your choice of displaying the grid by days/week, hours/day and a few other options. Since we’re using Twitter, I thought hours/day was most appropriate.

For the eventTemplate, it’s important to create an Ext.Template() object that means something to your users. Looking at the other examples of Ext Scheduler, you might see the name of the event, its start/end times, or other descriptive information. My example isn’t as cool… but you get the idea.

The only other thing I should point out is that your users will probably want a way to change the date range displayed by our scheduler grid. I added “Previous” and “Next” buttons which essentially alter the start/end date and reload our “event” data.

Step Four: Brag about your tool!

As I already pointed out, the Twitter API was a terrible choice for this demo because it doesn’t allow me to search for tweets by a selected date range. It was also a bad example because tweets don’t have start/end dates. Note to self: choose better examples next time!

Overall, my impression is that the Ext Scheduler will be an invaluable tool for most developers working with “events”. It’s easy to work with, offers an impressive set of features and should impress a lot of end-users. I would encourage everyone to check out the other Ext Scheduler examples and see for yourself!

JavaScript Tabs: ExtCore vs jQuery UI

Thursday, January 21st, 2010

A while back, I built a website for a client using jQuery 1.3 because I needed a slide-show widget for the homepage. More recently I’ve been using ExtCore for small website widgets – mainly because I’m a bigger fan of ExtJS than jQuery. (ExtCore also didn’t exist at the time I built that website).

Long story short, this particular client (a restaurant) asked me to add some new content to their menu. Rather than expecting the user to scroll down a lengthy list of mouthwatering lunch options, I suggested that we add tabs to the menu in order to logically separate the menu items.

Since I already had jQuery 1.3 running the slide-show on this website I simply decided to build the menu tabs in jQuery to maintain consistency. But I was suddenly struck by an idea: why not compare how ExtCore and jQuery UI create tabs from HTML markup!

ExtCore

ExtCore can be downloaded from the ExtJS website, and an online demo of the simple tabs can be seen here.

The first step to building tabs from HTML markup using ExtCore is to reference ext-core.js in your page header. You also need to include the tabs.css file and the “images” folder containing the necessary 5 background images. (These can be found under “/examples/tabs/” of your ExtCore download ZIP.)

Note: I’m using ExtCore 3.0, although I believe 3.1 is available for download.

Next, we need to add the appropriate HTML markup for our tabs. Here’s a quick example.

ExtCore HTML Markup

As you can see from the picture above, ExtCore takes a wrapping DIV element (class “tab_container”) and converts a nested unordered list into the tabs. Subsequent child DIV elements contain the markup for each tab’s content. (The source code in this example is taken directly from the ExtCore tab example.)

The only thing to notice is that each DIV element has a CSS class assigned to it – these classes are essential to proper tab theming. The DOM ID properties are used to click back-and-forth between tabs.

Lastly, you need to include a JavaScript snippet which converts your HTML markup into a fancy tabbed widget:

ExtCore JavaScript Code

jQuery UI

jQuery UI has a tab widget which is dependant on the larger jQuery library. An online demo of their tab widget can be seen here.

The first step to using tabbed content with jQuery is to reference:

  • jquery-1.3.2.min.js
  • jquery-ui-1.7.2.min.js

Your file versions may differ (I think jQuery 1.4 was just released), but these are the versions I’m using. I’m also using the “smoothness” theme – for some reason jQuery UI would not allow me to download the package without specifying a theme. (That may affect my analysis for speed in the next section.)

You will also need to include the CSS file and images folder included with your download of jQuery UI. In my case, it’s jquery-ui-1.7.2.css and an “images” folder containing 13 background images.

Next, write your HTML markup:

jQuery HTML Markup

Compared to ExtCore, jQuery UI expects less HTML markup as we lose several layers of nested DIV elements. The most obvious difference between jQuery UI and ExtCore is probably that jQuery UI doesn’t need the extra CSS classes applied to the DIV elements.

Next, we add our JavaScript snippet:

jQuery JavaScript Code

Again, jQuery UI expects less code to generate the tabbed widget.

A Deeper Look

Let’s take a look at the file sizes for each library. This is about as un-scientific a study as it can get; I’m using Firebug’s “Net” tab to grab file size and download speed numbers. These numbers will probably be different for you because of any number of factors… but you get the idea.

As I already mentioned, ExtCore requires 1 JavaScript file, 1 CSS file and only 5 background images:

  • ext-core.js (78.9 KB, 156ms)
  • Ext.tabs.css (1.3 KB, 147ms)
  • 5 png files (2.8-2.9 KB each, average 107ms)

Combing the file sizes and their download times (on my home network), you get a total of roughly 94.7 KB taking 838ms.

jQuery UI requires 2 JavaScript files, 1 CSS file and 13 background images (again, with the “smoothness” theme):

  • jquery-1.3.2.min.js (55.9 KB, 116ms)
  • jquery-ui-1.7.2.min.js (188.1 KB, 221ms)
  • 13 png files (22.3 KB total*)

*Something interesting I noticed about the jQuery UI tabs is that my page only seemed to load 5 of the 13 background images, totaling something like 605 bytes and a total of 684ms. Perhaps someone more familiar with jQuery can explain that to me… I didn’t dig deep enough to figure out what was going on, but I’ll base my total on what Firebug says. I’m guessing that I’m not using all of the CSS background images for this theme.

Overall, that brings jQuery UI tabs to a total of roughly 245 KB taking 1021ms.

What Does That Even Mean?

According to my inaccurate, quasi-scientific study it appears that ExtCore requires slightly more code than jQuery UI. On the other hand, ExtCore also appears to be downloaded by my browser more quickly than jQuery UI. In reality, those numbers probably offset each other as the extra markup required by ExtCore increases the HTML file size. The fact that I’m using a theme on jQuery UI probably also has a slight impact on performance.

Which do I prefer?

In essence, both libraries create tabbed widgets from the same basic HTML markup – though the differences are significant enough that they’re not cross-compatible.

Judging both frameworks as they stand in my examples, I will say that I like the conciseness (is that a word?) of jQuery with regards to both HTML markup and JavaScript code. But I also like that ExtCore requires fewer files. As someone who uses the larger ExtJS framework a great deal, I’ll say that I am very likely to choose ExtCore over jQuery UI most days of the week.

Are there any ExtCore or jQuery UI users out there? What do you think?

ExtJS Unit Testing now on Google Code

Thursday, December 17th, 2009

Although I’ve been meaning to do this for a while now, I finally released the ExtJS Unit Testing platform as an open source project on Google Code!

I’ve been talking about the need for a solid JavaScript unit testing platform for a while, specifically in relation to ExtJS. I gave a presentation on the subject a few months ago and have received some great feedback from the ExtJS community. I encourage you to take a look – I find it extremely helpful in my own day-to-day development.

See the interactive demo here.

Although I’ve been involved with several projects in the past, this is the first open source project that I have started on my own – and I had to stumble my way through the SVN setup. As ExtJS 3.x was released under the GPL v3 license, the ExtJS licensing team advised me to use the same license for this project.

If anyone is interested in contributing (or just wants to submit bug/feature requests) please don’t hesitate to contact me.