Sencha Inc. | HTML5 Apps

Blog

HelloWorld with Ext JS 4

June 21, 2012 | Samuel Asher Rivello

Guest Blog Post: Samuel Asher Rivello of Rivello Multimedia Consulting (RMC). For readers who are new to Sencha but coming from a Flex background, this guest blog post provides useful context and reference to familiarize yourself with how Flex concepts map to Sencha concepts.

This tutorial will help you get started with Sencha Ext JS 4. The full source code and 3 HD Screencast Videos are available below.

Before You Start

To follow along with this tutorial, you’ll need to setup the development environment for Sencha. This includes a web browser, a web server, and a text editor (or code IDE). I’m using a Mac with Chrome browser, Mac Web Server, and Komodo Edit. Follow the setup instructions here in the Sencha Getting Started docs.

Hello World For Application Development

Typically, a Hello World program illustrates the quickest way to get anything (such as text) on the screen and publishing (or compiling) without errors. In this post, I have also added a few things. We see a Sencha component (Viewport), Sencha classpathing (src), a custom super class, a custom subclass, and an example of a mixin class (similar to multiple inheritance).

The Project Output

Here is the example app running. I show it running in both a desktop browser. Sencha also offers Sencha Touch, which is built specifically for mobile, but today I’m focusing on the desktop framework, Ext JS.

Debugging: In the chrome window, it’s clear that the bottom of the window is using Chrome’s Built-In View->Developer->Developer’s Tools, and Sencha Ext JS outputs to it very nicely.

Screenshot
In Chrome on Mac

The Project File Structure

Sencha recommends an optional folder structure in their official Getting Started. I chose to use the following structure:

Screenshot

The Entry Point

You can see the index.html loads three external files.

<html>
<head>
    <title>Hello World</title>
 
    <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="./libs/resources/css/ext-all.css">
 
    <!-- LIBS -->
    <script type="text/javascript" src="./libs/ext-all-debug.js"></script>
 
    <!-- APP -->
    <script type="text/javascript" src="./app.js"></script>
 
</head>
<body></body>
</html>

Styles

I’m using the default CSS I found in some basic tutorials. I have not yet added/edited any styles.

Libs

There are a few choices that Ext JS gives you out of the box, each with its own distinct advantages and tradeoffs. You only need to use one.

Here is a rundown of each of the files.

  • ext-all-debug-w-comments.js – Debug version of the entire framework, with comments. This is the largest file of the bunch and requires the most processing to display in browsers.
  • ext-all-debug.js – Same as above, but without the comments. Still very large, but very good for debugging in most cases.
  • ext-all.js – The entire framework concatenated and minified. Debugging is impossible with this file, so it should be used for production systems only.
  • ext-debug.js – This file contains the Ext JS foundation and whitespace. With this file, you can remote load all of Ext JS, as needed, and it provides the best debugging experience. The tradeoff is that it’s the slowest.
  • ext.js – The minified version of ext-debug.js.

App

The app.js file is the entry point for your custom code. It’s where you put all your custom code as well as the ‘src’ folder and the ‘assets’ folder. Within my custom code, I show off a few interesting things:

Components

I have not dug deep into the Sencha Component library, but there are many good-looking components. There are components for Accessibility, Grids, Charts, Tabs, Windows, Trees, Layout, Managers, Drawing, Drag and Drop, Toolbars, Menus, ComboBox, DataView, Forms, MVC, and more! Here is a simple example of a ViewPort (basically a 100% by 100% canvas within which you can put panels or other things).

testSomeUI: function() {
    Ext.create('Ext.container.Viewport', {
        name : "viewPort2",
        layout: 'fit',
        items: [
            {
                title: 'My Viewport',
                html : 'Hello World!'
            }
        ]
    });
},

Classpathing

Sencha has a nice way of separating your code into classes, and your classes into packages. The root of all your packages is your source folder (or your ‘classpath’ in Adobe Flex parlance). Classes/packages help greatly with both organization and debugging (breakpoints and errors show you more clearly where the problem is).

First, I’ll configure one or more classpaths:

Ext.Loader.setConfig({
    enabled : true,
    paths   : {
        com : "src/com"
    }
});

And to load and use a class from the main app:

// SUPER CLASS
var myBeer = Ext.create('com.rmc.projects.helloworld.Beer', 'Budweiser');      
console.log ("myBeer.brandName: " + myBeer.brandName );
console.log (myBeer.drink());
 
// CHILD CLASS
var myLightBeer = Ext.create('com.rmc.projects.helloworld.LightBeer', 'BudLight');      
console.log ("myLightBeer.brandName: " +myLightBeer.brandName );
console.log (myLightBeer.drink());
 
// MIXIN
//  Because of 'MixinCheers.js' we can call 'cheers()'
myLightBeer.cheers();
 

I read in the documentation that the process is called ‘dynamically loading’ classes. Coming from Flex, it’s great that this ‘feels just like Flex.’ Classes can import each other as needed, and then you just run the program. Since JavaScript does not natively support OOP development just about every HTML5 framework requires the developer to use some framework-level conventions to mimic OOP. In the case of Sencha Ext JS, it works quite nicely.

Here is the super class:

Ext.define('com.rmc.projects.helloworld.Beer', {
 
    // --------------------------------------
    // Properties
    // --------------------------------------
    brandName: 'Unknown',
    calories: 0,
 
    // --------------------------------------
    // Constructor
    // --------------------------------------
    constructor: function(brandName) {
 
        // SUPER
 
        // EVENTS
 
        // VARIABLES
 
        // PROPERTIES
        this.calories = 200;
        if (brandName) {
            this.brandName = brandName;
        }
 
        // METHODS
 
        // RETURN
        return this;
    },
 
    // --------------------------------------
    // Methods
    // --------------------------------------
    drink: function() {
 
        return "The beer '"+ this.brandName+"' was drank. Calories : " + this.calories;
    }
 
});

Here is a subclass, which extends that super class:

Ext.define('com.rmc.projects.helloworld.LightBeer', {
 
    // --------------------------------------
    // Properties
    // --------------------------------------
    extend : "com.rmc.projects.helloworld.Beer",
 
    mixins: {
        ch: 'com.rmc.projects.helloworld.MixinCheers'
    },
 
    // --------------------------------------
    // Constructor
    // --------------------------------------
    constructor: function(brandName) {
 
        // SUPER
        this.superclass.constructor.apply(this, [brandName]);
 
        // EVENTS
 
        // VARIABLES
 
        // PROPERTIES
        this.calories = 100;
 
        // METHODS
 
        // RETURN
        return this;
    },
 
    // --------------------------------------
    // Methods
    // --------------------------------------
 
 
});

Here is a mixin class which the subclass uses:

Ext.define('com.rmc.projects.helloworld.MixinCheers', {
 
    // --------------------------------------
    // Properties
    // --------------------------------------
 
    // --------------------------------------
    // Constructor
    // --------------------------------------
 
    // --------------------------------------
    // Methods
    // --------------------------------------
    cheers: function() {
        console.log ("Cheers!");
    },
 
 
});

Ext JS MVC Template

If you enjoyed the ‘Hello World’ example above, here is something more advanced for you. In the spirit of the Robotlegs MVC Templates I created for AS3/Flex projects, I created an Ext JS MVC Template.

The idea of the template is to create (and later evolve slightly) a polished, simple example of an MVC app. This can serve as a starting point for all new Ext JS projects. MVC is a popular methodology to separate the model (data), view (user interface stuff), and controller (the ‘what’ that happens when you click UI and stuff). The app features a simple UI with ‘load’ and ‘clear’ buttons. The load (See ‘Figure 1?) button from the view communicates to the controller, which loads data from the model into the view. Clear works in a similar way (See ‘Figure 2?). It’s very basic, but illustrates some key concepts about Sencha Ext JS.

Screenshot
Figure 1

Screenshot
Figure 2

Conclusion

I’m happy with what I see in Sencha Ext JS. The framework adds to JavaScript in a great way. The styling system is very flexible and robust, and the components look and feel great.

Resources

Written by Samuel Asher Rivello
Samuel Asher Rivello is the principal of Rivello Multimedia Consulting (RMC), which offers services including software architecture, consulting, development and training. Sam has 12 years experience with the Flash Platform. He is an Adobe Flex Champion whose skills and experience transfer well to HTML5 based frameworks such as Sencha.

Share this post:
Leave a reply

There are 20 responses. Add yours.

MCBL

2 years ago

Why and iOS example? Isn’t Ext JS for desktop?

Dmitry Pashkevich

2 years ago

What the heck is that? Sencha, please control the quality of posts on your blog!

Lening Vergelijking

2 years ago

Please check the quality of your posts, this is rubbish!!!

Bob Obringer

2 years ago

I disagree with the above posters about this being rubbish, I do think this article is pretty useful in explaining the use of POJOs (in this case, Plain Old JavaScript Objects).

But there are a few things that aren’t quite right.

- The use of properties directly on the object.  This is very pre Ext4ish.  Shouldn’t brandName and calories be wrapped in a config:{} allowing Ext to synthesize the standard getters and setters?

- Explaining dynamic classloading is fine, but it’s much more powerful when explained in the context of MVC.

- Other than demonstrating dynamic classloading in extending classes, I’m not quite sure this really sets up developers with a real understanding of how to use this in a practical way.  You learn something… but the knowledge you gain is pretty limited.

Les

2 years ago

There’s no need to return ‘this’ from the constructor.  It will be implicitly returned even if the line “return this;” is not in the class code.

Dmitry Pashkevich

2 years ago

@Bob Obringer, I didn’t mean to say that “Hello World” articles are useless, I was talking about the way this specific article is written. I agree with your points but on top of that I believe that the article should be completely rewritten in order to be helpful for newcomers.

Anyway, I took some time to make my own points to support my feedback.

1) The article briefly touches many different aspects instead of just focusing on the shortest and simplest Hello World example (it started well though but then the author got carried away)

2) The article lacks cohesion, its parts are not well connected
2a) The iOS example and reference to Sencha Touch shouldn’t be here, they only add noise
2b) I also think that subclassing examples (with beer) don’t belong here, you can write a separate article “Intro to ExtJS Class System” which I believe already exists
2c) The section “Ext JS MVC Template” really wastes lots of space in the article. If the author doesn’t want to go into details about his MVC Template (which, again, can easily be a topic for a separate post) he can just leave the first paragraph with a link to the source in the end. No need of posting large blurry screenshots that are not very useful.

3) A couple of minor things that are not very good:
* Even the ExtJS library itself seldom uses namespaces deeper than 4 nodes. Do you really need to complicate your example with ‘com.rmc.projects.helloworld.LightBeer’? This is not Java! JavaScript is not efficient with names like that.
* Starting with version 4, Extjs supports “this.callParent()” instead of “this.superclass.constructor.apply(this, [brandName]);”

4) Finally, the language of the article can be better. It’s fine if the author posts this as “notes to myself” on his personal blog, but it needs more clarity and organization to be put in the official Sencha blog.

In conclusion, the article isn’t very friendly to a newcomer. While it does bring some pieces of knowledge it also brings confusion and lacks focus. Please work on that.

Bob Obringer

2 years ago

@Dmitry

Well said… you’ve done a much more detailed job analyzing the whole thing than I did and your points are spot on.

Huid Verzorging

2 years ago

Well said Could not agree more. Great point of view!!

Geld

2 years ago

Wtf is is this posted why is this posted is there no standard quality?

Tand Bleken

2 years ago

Dimitry could not agree more with you

Balaji N

2 years ago

I’m working with Ext JS for quite some years.  Honestly speaking, when I started reading this blog “what the heck is going on” is the first glimpse I got.  Definitely not intended for the beginners.  Agree 100% with @Dmitry.

Joeri

2 years ago

Let’s see the articles all you armchair critics have written? Maybe you can have some respect for the author’s efforts instead of this slash-and-burn commenting?

Dmitry Pashkevich

2 years ago

@Joeri
I never said I’m a pro. I’m here to learn and I’m used to getting quality material in this blog’s feed.

The guys at Sencha put quite a lot of effort into the Learning Center where the blog is a part of it. I’m really excited that the community around ExtJS and Sencha Touch keeps expanding, and people with Flash/Flex and other background come here and share their experience, this affects me and all other front-end developers in the long run. But again, this is the official corporate blog of Sencha Inc. and it’s natural that there are quality standards ruling its content.

jcarrillo

2 years ago

Ext 4 is a great framework with good components but it is very slow! Sencha Team is working on it or not? I would like to use the framework for my enterprise developement but if the Sencha Team dont do nothing quikly then they will lost potencial customers.

Roberto

2 years ago

No tutorial should be offered without using ExtJS MVC. Nothing else to say.

Jay Garcia

2 years ago

@Roberto,

Really? How do you explain how to create an element? MVC? How about event listeners on an element? MVC?

Jay Garcia

2 years ago

This is a great article, though the long namespace “com.rmc.projects.” is not really needed in the world of JavaScript, but if it helps people from the Flex world understand, go for it! 

Also,
this.superclass.constructor.apply(this, [brandName]);

needs to be changed to

this.callParent(arguments);

Keep the good work, Samuel! Thanks for taking the time to write on the Sencha Blog.

Thank You

2 years ago

Thank You!

It will be nice to see a tutorial about how to set and build a very large ExtJS application.

Nick

2 years ago

nice application! keep going!

Sharad Chandra

2 years ago

How to create WCF rest service for Sencha touch 2. Is below code are correct ?

In interface:-


      [OperationContract]
      [WebInvoke(Method = “GET”, UriTemplate = “TestSenchaAdd?Dn={Dn}”, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
      System.IO.Stream TestSenchaAdd(string Dn);

Is there any thing need to implement in service for sencha touch 2. above service is working fine for all other mobile services except sencha .

Comments are Gravatar enabled. Your email address will not be shown.

Commenting is not available in this channel entry.