Tutorial: Full-stack JavaScript for the Enterprise. Getting started with: Ext JS, Node.js, Express, MongoDB and Docker. (5)

Posted on in Docker Environment Ext JS 6 MongoDB Node JS NoSQL

This is part V of the tutorial, and covers how the Ext JS client app can consume the server Node.js API

Let the Ext JS app consume your API

By now we have a working back-end with Node, and a working front-end with Sencha.
Now we are ready to modify our Sencha app, so we can consume our back-end data and see it all in action!

It’s a simple client application with CRUD functionality for the Users model. With other words, we can create (POST) new users, read users and user details (GET), update existing users (PUT), and remove a user (DELETE).

I’ve added the codebase to Github, so let’s go through it, file by file. We will focus on the Classic Desktop view first, later we will create a mobile phone view.

Classic

https://github.com/savelee/docker-ext-client/blob/master/classic/src/Application.js

The application doesn’t auto create a viewport. Instead I’ve created a custom launch function, which either creates a login view (with the viewport plugin enabled), or the main interface with the viewport plugin enabled. It depends on the authorization token, if you have one on the device, it will auto login.

Take a look into the following files:

Here you can see the login panel. It’s actually a non-closable, non-draggable window, locked in the middle of the screen. The user can enter the username and password, which will be posted to the Node Express server. In case the username and password match with what’s in the database, it will return a token. In the success callback, we will save the token to the browser local storage.

Notice that we created two ViewControllers. One which will be shared by the classic and modern view. (This one contains the functionality to communicate with the back-end, since that’s view irrelevant.) The other ViewController, extends from the shared VC. This is the VC that contains an alias, and is bound to the classic view.

Note that although we Bcrypt the passwords in the database. It’s not secure to send passwords over HTTP. An attacker could very easily sniff the username and password that will be in the POST. Therefore enter: https://letsencrypt.org/. You could very easily create a free SSL certificate. You can find a guide here: https://letsencrypt.org/getting-started/ so you could set this up in no time.
It’s actually very easy, as long as you have console access to your webserver.

Let's dive further into our Ext JS code:

That’s the main viewport. It’s pretty much the same as the generated one from Sencha Cmd. We’ve just added a logout button. (which will destroy the main viewport, and remove the token from the localstorage.)

This is just a view with a grid. It shows a grid column for the first_name, last_name, email and an action column to remove the user from the grid. The functionality for this can be found in:

onRemove makes an AJAX call with the DELETE method, it makes a call to a URL that contains a user id.

When you click on a row in the grid, it will open a popup window, which contains the form.
I’ve implemented a renderConfig, which will hold the selected record. That way, as soon as the window will be created, and you run setRecord() on the form, it will run updateRecord() and load the record in the form, since the model fields map the form fields.

When you submit the form, you will get into the beforeSubmit() method. Here we just determine if the form contains a hidden form field, which contains the user URL. If it does, it means, the form contains data, so every change made will be a PUT request. If the form is empty, we will add a new user, and therefore we POST to the /users overview URL. The AJAX request itself, can be found in the shared user VC.

And that’s it for the desktop view.

desktop

Modern

The mobile view re-uses most of the functionality that’s already there. What is new, are the mobile (phone) views:

If there’s a token available, it will add the main view to the viewport, else it adds a login view.

The login view is a container, which centers a login form in the middle of the screen.
It calls the login view controller, for the onLogin() method. This method uses the doLogin() method from the shared login view controller, which contains the AJAX POST call, to request a token. Once logged in, it will add the token to the local storage, and it will remove the login view from the viewport, and instead add the main view to the viewport.

The main view is just a tabpanel, with for now, just one tab. It contains a hidden back button, which will be enabled once you are in a form. And it contains a logout button, which calls the onLogout() method, which removes the token, and resets the views.
It contains a user tab, which has a card layout. It can switch between a grid view which list all the users, or a form, to edit one user.

This is the list view. It contains an itemTpl with the first_name, last_name, email, username and password. Once you tap an item, it slides in the userform.

This form contains also a toolbar with a Delete button. This toolbar will be hidden, when you open the form via the Add button. But when you tap an item, it’s visible, and the form will be prefilled with data. It contains similar functionality as in the classic toolkit. It holds a config with the record.
updateRecord() will be called, every time when you run setRecord().

Feel free to download the code base and play around with it.

mobile

By the end of this part of the tutorial, you will understand how the Sencha Ext JS client can consume the Node.js server API. In the next blog posts we will focus on getting familiar with Docker.

Read the next part

https://www.leeboonstra.com/developer/tutorial-full-stack-javascript-for-the-enterprise-getting-started-with-ext-js-node-js-express-mongodb-and-docker-6/

Advanced Sencha Cmd: Dealing with a multi Ext JS app infrastructure

Posted on in Cmd Environment Ext JS Ext JS 5 Ext JS 6

This guide will describe how to deal with an infrastructure, that contains multiple Ext JS apps.
It will discuss:

  • Local workspaces
  • How to split builds
  • How to modify file paths and output settings

About Workspaces

To support these, Sencha Cmd defines the concept of a “Workspace”. A Workspace is simply a folder that ultimately contains one or more apps (pages), frameworks, packages and other shared code or files.
The location of the Workspace root folder should be chosen to facilitate these needs as well as your source control requirements. Any generated applications/pages created in sub-folders of the Workspace folder regardless of their depth are considered to be members of the Workspace.

Though not a requirement, it is typically the case that the Workspace folder is the root folder in a source control repository.

To create a workspace, you will need to have a downloaded copy of the Ext JS framework on your hard disk, also you will need to have Sencha Cmd installed.
On the command-line navigate to the downloaded Ext JS sdk folder. From here, enter the following command:

sencha generate workspace [path to workspace]

This will generate the following folder structure:

workspace.json   # The JSON descriptor for the workspace.
ext          # A copy of the Ext JS sdk, examples/docs are stripped out
packages         # Empty folder, which will contain shared code / themes
.sencha/                # Sencha-specific files (e.g. configuration)
    workspace/          # Workspace-specific content (see below)
        sencha.cfg       # Configuration file for Sencha Cmd
        plugin.xml        # Plugin for Sencha Cmd

Within this workspace you can generate Ext JS apps, from the ext folder:

cd ext
sencha generate app MyApp ../[folder-name]

All applications within the workspace, can share the same Sencha ext folder, code packages (such as custom components, themes or locals) can be shared across both apps and also applications can find each other in the workspace. (for example, in case you want to extend from apps.)

For more information about workspaces see:

Splitting builds

By default, a workspace only matters on your development machine. Once you make a build:
sencha app build

Sencha will copy all the used framework classes and all your self written Sencha classes to a build folder. For production, all scripts will be minified. Also the Sass themes will be compiled to production ready css, and copied together with the resources.
This means, by default, all shared frameworks and code packages, will be duplicated in the production build, as they can run as stand-alones.

For most users, this behavior is exactly what they want. However, there are reasons, why people want to “split” their builds, and host code packages or frameworks separated from their app code.

Examples of such reasons are:

  • You are creating your own application framework. You are dynamically generating views, or maybe you are hosting the framework within a portal, expecting your code base will grow over time.
  • You are building a large application, with separated areas, such as an application, and an admin panel. Each of these areas, could be treated as an app itself. Which contains many views, controllers and models etc. It might be that you have different user groups visiting these apps. Why deliver them code, which they don’t need?
  • Your application became huge, and you want to split your scripts in smaller chunks.

For the last reason, there’s a good tutorial online: https://www.sencha.com/blog/blazingly-fast-load-times-for-apps-built-with-ext-js-and-sencha-touch/
Let’s dive into this topic, about splitting builds. Assuming you want to exclude the Sencha framework classes from your own app code.

In every sencha application folder, there’s a hidden .sencha folder. This hidden folder contains lots of build scripts, settings and metadata used by Sencha Cmd.
One of those files is: js-impl.xml, an Apache Ant build script, which contains an compile-js block, which takes care of filtering out all the used framework classes, and all your own JavaScript classes, to create a (minified) build:

It checks if, setting: enable.split.mode is set to true, and if so, it will split your framework with a minified, concatenated framework file & a minified, concatenated app.js file, which contains your own classes. Note, by default this setting is false.

Unfortunately, the code in the first block, doesn’t really work in Ext JS 6. But you can change it to something like below, to make it working again.
I've been playing around with this:

NOTE: I will need to test this further, but this code will need some more iterations though, I have the idea, you can union more, by tagging the Ext namespace.
Also, saving this script in js-impl.xml, is not a best practice. When you reinstall Sencha Cmd, and upgrade your app, you will loose everything that's inside the hidden .sencha folder. Instead you want to move this script out and leave it a build xml file within your project.

You can find a working example in my Github repository:
https://github.com/savelee/ext-workspace-demo/blob/master/app1/.sencha/app/js-impl.xml

In this example, I have 2 generated Sencha apps. MyApp1 and MyApp2. Both contain a custom build file, to make sure the framework will be filtered out of the final build.

Build properties

So where is this enable.split.mode setting coming from? It’s a property file, and the hidden .sencha folder, has many properties files. You can find them all in: default.properties.

To fine-tune your build, you could open production.properties, and add the props you like, for example:

enable.split.mode=true
build.out.framework.path=${build.out.base.path}/${app.output.framework.path}
app.output.framework=framework.js
app.output.framework.path=${app.output.framework}
app.output.framework.enable=false

Ideally you shouldn’t edit
the .properties files, these are located in the hidden sencha folder, so this means they will be overwritten when you update Sencha Cmd.
Additionally, I don’t recommend, checking .sencha and framework folders in source control systems such like Git. You don’t want to get merge errors, when other team members have newer versions of software, running on their machines.

So to make these changes, to make sure that the sencha build process, splits the build, you can make changes in the app.json file of your app:

"output": {
..
        "framework": {
          "path": "${workspace.build.dir}/${build.environment}/framework.js",
          "enable": true
        },
..

Move the framework.js outside the app build folder

Now that we know how to split builds, or you might want to move assets / scripts around.
By default it will include framework.js and app.js in the same application folder but this will be a file, which needs to be located on a central place.

Luckily with Ext JS, you are able to move around files very easily. Many things are configurable.

In the app.json file, there will be an output block. In this block, you can rename the files, change the extension from the index page. (for example, in case you want to change it to a jsp or php file…), and you are also able to change the base path.

Once the base path is changed, you probably will need to change all the other paths as well.
Have a look into the app.json file that I wrote, or the snippets below:
https://github.com/savelee/ext-workspace-demo/blob/master/app1/app.json

The output block:

"output": {
        "base": "${workspace.build.dir}/${build.environment}/",
        "page": "${app.name}/index.html", //you can change this to index.jsp
        "manifest": "${app.name}/${build.id}.json",
        "js": "${app.name}/${build.id}/app.js",
        "framework": {
          "path": "framework.js", //this will be the shared sencha framework stuff
          "enable": true
        },
        "resources": {
            "path": "${app.name}/${build.id}/resources",
            "shared": "resources"
        }...

The archivePath, to move the archives folder:

"archivePath": "${app.name}/archive/${build.id}",

The appCache block, to move the app.cache file. Note, it’s also located in the production block.

"appCache": {
            "path": "${app.name}/app.cache",
            "enable": false
},

The cache block, to move the delta folders:

"cache": {
        "enable": false,
        "deltas": "${app.name}/${build.id}/deltas"
},

Versioning Systems

I mentioned it before, there are a couple of scripts, you ideally don’t want to check into your source control. For Git, you can write a gitignore file, which blocks checking in the below files.
I’m sure, other versioning systems, can do the same.

There are some handy links, I like to share with you:

How to Upgrade a Sencha Touch App to Ext JS 6 Modern Toolkit – Part 3

Posted on in Ext JS 6 Sencha Touch

Advanced Universal Upgrade

This upgrade will take the most time, but your opportunities are endless. You will have the latest framework with all the new features and classes, and you can improve your application performance and code base with the new MVVM architecture. Plus, you can create universal cross-platform apps (or plan to do that in the future). Not only can you build applications for mobile phones or tablets, you can also support desktop or hybrid computers, with a component set specifically made for desktop usage.

To take this approach, my advice is to regenerate a folder structure with Sencha Cmd, with the same namespace, but this time as a universal app.

  1. Navigate to the ext framework folder and generate a project with:
    sencha generate app
    For example:
    ext> sencha generate app Dinmu ../dinmu3

    This will create a folder structure with the shared app folder, the classic folder for the classic toolkit, and a modern folder for the modern toolkit.

  2. Files

  3. Once you have this folder structure, you will need to think about which code you want to share, and which code you want to be unique for each experience.

Obviously, this means that you need to create new views, specific for desktop. (In the case of the weather application, I can assume that you already have an existing touch application, with modern toolkit views, so you will make new desktop views). Desktop components might require unique event listeners, so you probably will end up with additional view controllers. You can share view controllers from the app folder, by extending it, for example.

However, you could also choose to create unique data / models for desktop views. The screens are bigger, so you have more space to display additional data. Or maybe a mobile phone has different features (camera, geolocation, etc.) than a desktop application, so you might want to create different behaviour for certain devices. The good thing is that this is all possible. The trick here is that you move classes over from the app folder to either the classic or modern folders. You can learn more about creating universal apps in my previous blog post series.

What About File Sizes?

Are you interested in the file size of the build app.js and app.css of the Weather app? Have a look:

Sencha Touch
Ext JS 6 Modern – Basic
Ext JS 6 Modern – MVVM
app.js – minified
558kb
836kb
887kb
app.css – compiled
241kb
91kb
91kb

Ext JS 6 requires more advanced classes, so that’s why the total build will be a bit bigger. You can make your own code base smaller by switching to View Controllers, using data binding, and cleaning your model fields, which might get you an even smaller final build.

Also note, because of the new microloader, we can cache your applications way smarter, and applications can be made for offline use.

Triton Theme
Triton Theme
Triton Theme
Triton Theme

Conclusion

In this tutorial, I’ve explained how to migrate your Sencha Touch application to Ext JS 6 Modern toolkit. For me, the basic upgrade took a few hours, and the upgrade to MVVM took a morning. However, this is a pretty basic application with not many views.

Upgrading is easier than when you had to upgrade from Sencha Touch 1 to Sencha Touch 2, but it can take some time. It depends on whether you want to upgrade the pattern too, and if you have lots of custom components in your existing Sencha Touch app.

We have lots of professional services engineers, who migrate complex applications all the time, and they can help you with your application. Contact us for details.

Windows Theme

I do think it’s worth spending the time on upgrading your app with the MVVM pattern because:

  • You will be on the latest framework, and support the latest browsers and operating systems.
  • You can clean up your code base a lot.
  • The MVVM pattern can improve performance.
  • You can create desktop & mobile applications with one code base.
  • You will get all new classes, components, and themes.
  • You can use the new theme package structure, and compile themes much faster.

Because of the new Ext JS core, all newer Ext JS apps (version 5 and up) will be backwards compatible. That means it will be simpler to upgrade (just like Ext JS 5 to Ext JS 6 applications, which only require an upgrade through Cmd).

Do you support integration with external databases?

Posted on in Ext JS 5 & 6 Questions

In case you want to retrieve or save data in an external database, best practice is to use some server-side scripting.

Within the Sencha frameworks, sending and retrieving data works via a proxy. (http://docs-origin.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext.data.proxy.Proxy). (Ajax or JsonP) This proxy will be hooked to the serverside end point. The Sencha proxy can read (and write)
JSON or XML.

Can I use the Ext JS GPL?

Posted on in Ext JS 5 & 6 Questions

Ext JS GPL

GPL is opensource. You will have to share all your source code public and with Sencha.

  • You can't use GPL for commercial software.
  • You can't build your project with GPL and later change the license, the project needs to be created with the correct license from the start.
  • Sencha Architect won't work with GPL

See:
https://www.sencha.com/legal/open-source-faq/

Also, according to Apple AppStore rules, you are not allowed to add GPL projects to their stores.
See:
http://www.zdnet.com/article/no-gpl-apps-for-apples-app-store/]]>

What about Ext JS and ARIA support?

Posted on in Ext JS 5 & 6 Questions

It is understandable and expectable that an application built with Ext JS 4.2.2 will have poor accessibility support; the ARIA project was only starting at that time. Still it was better than nothing so it was released as a separate ext-aria package; if the application doesn't include ext-aria package then it will have no ARIA support to speak of.

Ext JS 5.0 was better with regards to accessibility and ARIA in particular, but the bulk of the effort was spent in making focus management and keyboard navigation work out of the box; screen reader support didn't improve much in 5.x and it was still necessary to include ext-aria package to get ARIA support in your app. If they didn't do that they would have better keyboard support than 4.x but no screen reader support (it was still in the package).

Ext JS 6.0 has accessibility support built in, there is no more external package to require. In addition, we have greatly improved keyboard navigation and screen reader support as well. That is why I recommended to upgrade to 6.0 if the customer needs accessibility. That said, Ext JS 6.0 is not a silver bullet and there is additional work that needs to be done on an application to make it accessible. We have a separate ARIA demo for accessibility evaluation; there will be a new, more realistic, accessibility example coming up soon.

Simple Techniques for Solving Common Sencha Coding Problems

Often when I’m teaching a Sencha Training class, students ask me to look at their apps because there’s a problem they don’t know how to fix. Since I didn’t write the code, it’s hard sometimes for me to give them a quick answer. However, I do have a set of simple techniques that filter out the most obvious problems.

In this tip, I’ll categorize a couple of most common problems and tackle them with some simple but effective strategies.

Problem: “I don’t see my data”

You are browsing through your app, but the data is not visible. Often, this problem is easy to fix.

“Here, try this:”

First, try to inspect the Store. You can do this from the browser console by running:

Ext.getStore(‘MyStore’).load();

This returns the Store object. You can drill through the data config and see if the array length is greater than zero.

If there is data available, something probably went wrong with rendering. Consider these possible issues:

Do the data fields map the fields in the Model?

Is the data array empty? In your browser developer toolbar, hit the Network tab. Do you get a status code 200? No? Then something went wrong with your request. Check your Model/Store proxy.

The request works correctly, but it still doesn’t display the data? Verify whether the data you get back is valid. For example, when you are using JSON data, you can copy the data response from the browser network tab into http://jsonlint.com or http://jsonplint.com/. You can also use your own written test data too.

Problem: “I can’t build my app”

Sencha Cmd won’t build your app. Most of the time, Sencha Cmd gives a clear explanation of what’s going on, or what needs to be changed. However, every now and then, I see problems where Sencha Cmd won’t build. and the error description is not clear. It might be that there is nothing wrong with your code. For example, your code runs perfectly on your local environment. It just won’t build.

“Here, try this:”

This trick is pretty radical, but most of the time it works. Generate a new application with the same namespace from the command line:

sencha generate app App ../myapp

Next, copy over the app folder, and make sure you take the changes over from app.js. Now try it again!

Problem: “Strange component-x behavior”

These types of problems are always the hardest ones. For example, suddenly multiple scrollbars show up in your grid. Or, you see a tab panel with the wrong styling. Testing these kind of problems within your app can be time consuming. Not only do you have to navigate through your app to get to this problem, there can also be many reasons why it’s broken.

“Here, try this:”

A common problem-solving technique for developers is to isolate the problem into smaller, more manageable chunks.

Isolate the problem

Let’s generate a new application with Sencha Cmd, again with the same namespace. Now, copy over the Class that contains the problems and test it. Do you see the same bugs? You can try to solve it in this test app. You can isolate it even further by trying to re-build your class from the ground up. Start with only the necessary code.

Did it work? There is nothing wrong with the framework, and there is nothing wrong with this Class. Something else must be wrong.

Switch to the default theme

Go back to your own app and try to switch to one of the Sencha default stylesheets. (Sencha Default StyleSheet in Sencha Touch, Neptune Theme in Ext JS) Does it finally work? Then there is something wrong in your custom StyleSheet. Is it still not working? At least now you know that your custom StyleSheet is correct. There might be something wrong with your nesting. Or maybe you used the wrong layout?

Query for Components

Do you have problems with querying for Components? You can easily query components from your browsers dev console:

Ext.ComponentQuery.query('button[action=”test”]');

Does it return an empty array? Then there you go! Or maybe it does return the components, but you made a timing mistake. That can often be the case when you’re working with callbacks. When your code is executed, the component may not be rendered on the screen.

Common Debugging Techniques

As a developer, you will often run into bugs and problems that you have to solve. But hey, that’s what makes our jobs challenging, right?

Aside from the above mentioned techniques, there are also a couple of standard tricks. First of all, know the framework and know your tools. Read the API Docs (or even better, browse through the framework code).

Switch to one of the debugging frameworks. The advantage is that it often shows extra log messages, and you can directly read through the framework code. For Sencha Touch projects, open app.json and change the framework temporarily:

"js": [
{
"path": "../touch/sencha-touch-all-debug.js",
"x-bootstrap": true
},

For Ext JS projects, open index.html and change the framework temporarily:


Your browser dev tools can help (Google Chrome or Firebug). Also, there are some handy plugins for developing Sencha code: Illuminations and App Inspector for Sencha.

Do you quickly want to prototype something? Try Sencha Fiddle. There are great tools for testing available, such as Siesta.

And last but not least, if none of these techniques help you and you are staring at your code for hours (or even days)... take a break! Often, when you take a break and free your mind, you can solve it right away. Especially if you’ve made spelling mistakes or (case sensitive) typos that can cause hours of frustration because you just don’t see them.

Looking for more help? Check out one of the Sencha Ext JS and Sencha Touch training classes located around the world, or join an online class.

How to Set Up Your Sencha Environment

Posted on in Sencha

While teaching Sencha app camps and training classes, every now and then I see common app build problems related to the installation of the Sencha environment. It’s important to understand the dependencies to get yourself up to speed. In this article, I’ll provide an overview of the dependencies and show you how to get everything set up correctly.

Getting Started

Let’s take a look at the dependencies, in order to use Sencha Cmd as a build and code generation tool, you will need to have the following setup, as a base:

  • Java Runtime Environment
  • Ruby
  • Sencha Cmd
  • Sencha Frameworks

Java, Ruby and Sencha Cmd must be available from the command line to use these features. When installing Java, Ruby or Sencha Cmd, usually the installer will add it to the PATH system variable. However, sometimes these variables get lost or were not added at all. When that’s the case, these tools are not available on the command line, so Sencha Cmd can’t access them. It’s very important that these paths are set, so let’s look into how to set the system path variable. If you know this process, you can skip the next paragraph.

How to Set a System Variable

I will explain how to add a variable to the PATH on different systems. Later in this article, I will discuss the variables and paths to set.

Windows

  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8

Mac OSX / Linux

  • Bash shell

Windows XP

  1. Start -> Control Panel -> System -> Advanced
  2. Click on Environment Variables, under System Variables, find PATH, and click on it.
  3. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and location of the class as the value.
  4. Close the window and reopen the command prompt window.

Windows Vista

  1. Right click My Computer icon
  2. Choose Properties from the context menu
  3. Click Advanced tab (Advanced system settings link in Vista)
  4. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and location of the class as the value.
  5. Close the window and reopen the command prompt window.

Windows 7

  1. Select Computer from the Start menu
  2. Choose System Properties from the context menu
  3. Click Advanced system settings > Advanced tab
  4. Click on Environment Variables, under System Variables, find PATH, and click on it.
  5. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and location of the class as the value.
  6. Close the window and reopen the command prompt window.

Windows 8

  1. Drag the Mouse pointer to the Right bottom corner of the screen
  2. Click on the Search icon and type: Control Panel
  3. Click on Control Panel > System > Advanced
  4. Click on Environment Variables, under System Variables, find PATH, and click on it.
  5. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and location of the class as the value.
  6. Close the window and reopen the command prompt window.

Mac OSX / Linux

  1. Edit the bash profile (~/ .bash_profile)
  2. Modify PATH variable, write the following line, with the path to one of the tools:
    1. export PATH=<PATH-TO-ADD-HERE>:$PATH
  3. Save and close the file and open a new terminal window

NOTE: The .bash_profile is a hidden file, to enable hidden files in Finder, run the following command from the command line:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Java Runtime Environment

Java Runtime Environment is required by the build tools of Sencha Architect (Sencha Cmd). You will need a valid build to display your app stylesheet, so it’s necessary to have Java installed.

To check if you have Java running, type the command below from the command line. (Mac OSX users, open the terminal, Windows open the command line by entering cmd from the start screen.)

java -version

If correctly installed, it should output the version number. For example:

>java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

The JRE is the Java Runtime Environment. It’s an implementation of the Java Virtual Machine which actually executes Java programs. Without JRE. you can only compile the application but you can’t run it.

The JDK is the Java Development Kit. It’s a software bundle that you can use to develop Java based software. Since JRE contains the JVM which executes the byte code generated from the javac compiler, you need to add your JRE path to JAVA_HOME variable from the environment variables.

Note: the JDK contains the JRE, so if you have set your PATH properly you shouldn't need a separate entry for the JRE.

You can download Java JRE 1.7 or the JDK.

Windows users:

Run these commands from the command line to add Java to your PATH:

variable name:
JAVA_HOME
variable value:
c:jdk1.7.0_40
variable name:
PATH
variable value:
%PATH%;%JAVA_HOME%bin

Mac OSX / Linux users:

Assume Java is installed in /Library/Java/JavaVirtualMachines/<java version>/. Run these commands in your terminal to add Java to your PATH:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

For more information see: http://java.com/en/download/help/path.xml

Ruby

Sencha Architect uses Ruby during the app build process when building a theme. Theming in Sencha frameworks requires Sass & Compass. You don’t need to install those two dependencies since they ship with Sencha Cmd and Sencha Architect, but Sass & Compass run on top of Ruby, so Ruby is required.

To check if Ruby is correctly installed, run the command below from the command line. (Mac OSX users, open the terminal, Windows open the command line by entering cmd from the start screen.)

ruby -v

If correctly installed, it should output the version number. For example:

> ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [universal.x86_64-darwin13]

Ruby is automatically installed on Mac OSX machines. Windows users will have to download Ruby. Sencha Architect works with both Ruby 1.9 and Ruby 2.0 versions.

You can download Ruby.

Make sure you run the Ruby installer with admin rights (right click on the installer executable and select run as administrator.) During the installation, you will have to check the checkbox which asks to add Ruby to your PATH variables.

Sencha Cmd

To build applications with Sencha Architect, it requires the build tools, Sencha Cmd. Since Sencha Architect runs on top of Sencha Cmd, you don’t need to install Sencha Cmd because it’s included with Sencha Architect.

Sencha Cmd is a very useful set of tools. You can not only build your applications with it, you can also build themes, generate code or use the built-in (Jetty 8.1.7) web server.

You can test if Sencha Cmd is available from the command line by entering the following:

sencha which

If correctly installed, it should output the version number. For example:

> sencha which
Sencha Cmd v5.0.0.116
/Users/leeboonstra/bin/Sencha/Cmd/5.0.0.116/

It requires that Sencha Cmd is added to your PATH variables. This should happen automatically when installing Sencha Architect or Sencha Cmd. If it’s not available, you can download and reinstall Sencha Cmd:, or you can add the paths manually on the command line:

Windows users:

Assume Sencha Cmd is installed in c:senchacmd5.0.0.116.

variable name:
PATH
variable value:
%PATH%;c:senchacmd5.0.0.116

Mac OSX / Linux users:

Assume Sencha Cmd is installed in ~/bin/sencha/cmd/5.0.0.116.

export PATH=~/bin/Sencha/Cmd/5.0.0.116:$PATH

The build tools also need to be enabled in Sencha Architect. Verify Sencha Cmd is enabled by navigating to Settings > Project Settings Framework:

Sencha Frameworks

Check out the following Sencha product pages, to download the latest downloads for Ext JS or Sencha Touch.
Sencha Touch, Sencha's framework to create multi-device/mobile apps is free to use, and can be found here:
http://www.sencha.com/products/touch/. Ext JS is Sencha's framework to create desktop/tablet web applications with, for more information take a look into the product page at: http://www.sencha.com/products/ext/.

In case you have questions about your Sencha setup, feel free to comment underneath this post!

Ext JS 6

Update:
I wrote a new setup guide for Ext JS 6 development. Please check this link:
http://se.sencha.com/setup-guide/

Creating Theme-Specific Overrides in Ext JS

Posted on in CSS Ext JS Sass Sencha

Ext JS provides a number of functions that make it simple to create and work with classes. It also provides a series of functions to extend or override existing JavaScript classes. This means you can add behaviors and create your own classes, or override the behavior of some functions. In this article, we will show you how to use theme-specific class overrides.

You probably already know how to create an Ext JS class override. For example, you might want to change default behavior or patch the framework. In that case, you would create the class override using this code:

Ext.define('SomeClassName', {
    override : 'Ext.panel.Panel'
 
    //the override: by default, all panels will have a 200px width
    width : 200 
});

The first questions that come up are: what do you name this override class and where do you put it. You may be creating a class override that is specific to a theme. Wouldn’t it be nice, to have this JavaScript override bundled together with your custom theme? For example, in your custom theme, all panels should have a box-shadow. Or perhaps, you created an awesome CSS3 animation that will be visible any time you open a popup window. Unfortunately, the old versions of Internet Explorer can’t handle CSS3, so you might want to write a JavaScript fallback. In both cases, the default functionality change is visual. So, where in your file structure can you create these overrides, so they don’t break any other themes?

The trick is the overrides folder. With Sencha Cmd 3.1, it’s possible for applications and packages to save class overrides in the overrides folder. By default, when you generate a (theme) package, it already contains such a folder, and it has been set up to support overrides.

Let’s create a JavaScript fallback. For a simple animation, we will animate the opacity when opening a popup window.

Create the following file structure in your theme package, (let’s assume the name of this package is called: MyTheme ):

packages
> MyTheme
> > overrides
> > > window
> > > > Window.js

This file structure maps to the file structure of the framework for Ext.window.Window.

Let’s define the class:

Ext.define('MyTheme.window.Window', {
 
});

This class will override from Ext.window.Window:

Ext.define('MyTheme.window.Window', {
    override : 'Ext.window.Window'
 
});

Let’s test if this override works. First, run this from the command-line:

sencha app refresh

At this point, the previous code won’t change any functionality yet. Let’s output a console log as soon as the class is created, and test it in a browser:

Ext.define('MyTheme.window.Window', {
    override : 'Ext.window.Window'
 
}, function(){
    console.log("Oh yes, my override works!");
});

Let’s create the custom behavior. This override will add an animation on the beforeshow listener of a window:

listeners: {
    beforeshow: function(mywindow){
 
    }
}

The beforeshow listener will create a new animation (Ext.fx.Anim), so first you have to require the animation in your class:

requires: ['Ext.fx.Anim'],

Next, you include the code for creating the animation in the beforeshow event. For now, we will create a very simple animation, which changes the opacity to smoothly display the window (mywindow) from hidden to 100% visibility:

Ext.create('Ext.fx.Anim', {
    target: mywindow, //argument of the beforeshow event
    duration: 1000, //ms
    from: {
        opacity: 0
    },
    to: {
        opacity: 1
    }
});

Now, you can test if the animation works.

To top it off, let’s create a nice CSS3 animation for the modern browsers as well. We will wrap the Ext JS animation into a check that will only execute when the browser is an old version of Internet Explorer (IE9 or lower):

if(Ext.isIE9m) {
 
}

Confirm your code looks like this:

Ext.define('MyTheme.window.Window', {
    override : 'Ext.window.Window',
 
    requires: ['Ext.fx.Anim'],
    closeAction: 'hide',
    listeners: {
        beforeshow: function(mywindow){
 
            if(Ext.isIE9m) {
                Ext.create('Ext.fx.Anim', {
                    target: mywindow,
                    duration: 1000,
                    from: {
                        opacity: 0
                    },
                    to: {
                        opacity: 1
                    }
                }); 
            }
        }
    }
});

The only thing that is missing is the Sass code for the CSS3 animation. We will use Compass for that.

In the theme package, we can add the following Sass code to packages/MyTheme/sass/src/window/Window.scss. The code below shows the same animation that we coded in the JavaScript file:

@import "compass/css3/transition";
 
.x-window.x-hide-offsets {
    @include opacity(0);
}
 
.x-window {
    @include single-transition(opacity, 1000ms);
    @include opacity(1);
}

You will need to compile the Sass stylesheet to production-ready CSS code. Since this is included in Sencha Cmd and the Sencha build process, the Sass stylesheet will be automatically compiled when building the application with Sencha Cmd.

For now, we don’t need to build the whole application, we just want to quickly test the animation and only compile the stylesheet. You can achieve this by running one of the following commands from the command-line:

sencha ant sass

or

sencha app watch

The first command runs the Apache Ant task to compile the Sass once. The second command is more powerful, but it requires you to download and install Java Development Kit 7. You can compare sencha app watch with the Compass command: compass watch. Sencha Cmd watches the app and every time you hit save, Sencha Cmd builds your app and compiles your Sass Stylesheets. When changes are detected, only the minimum amount of work necessary is performed to bring your app and its CSS up to date, saving you from rebuilding your Sass.

Voila — the animation works in old and new browsers.

If you’d like to learn more about this and many other advanced Ext JS theming techniques, take our Advanced Theming Ext JS course. Check out http://www.sencha.com/training/ to join one of the Theme331 Advanced Theming classes located around the world or join an online class.

Create dynamic Sencha models from your server-side

Posted on in Ext JS Sencha Sencha Touch

Every now and then I get this question in my Sencha training classes: "How can I dynamically create Sencha Models from my server-side?", or "How can I dynamically inject fields?" Normally you would define a Sencha Model like this:

Ext.define('App.model.MyModel', {
  extend: 'Ext.data.Model',
  
  fields: [{
     name: 'id',
     type: 'int'
  }, {
    name: 'firstname',
    type: 'string'
  }, {
    name: 'lastname',
    type: 'string'
  }]

});

The previous code is a Model class definition written in Ext JS. In Sencha Touch, it's almost the same, you would wrap the fields array in a config object. Defining Models this way, is perfect, but sometimes you would like to generate your Models from the server-side. For example, because you are using lots of fields, field names often change and you don't want to maintain the fields on two places (server-side vs. client-side). Mind you, also the data-type or field validations, needs to be in sync on both places, to not experience funny behavior.

So? Is it possible to create dynamic models? How does that work?

Let's say we have a PHP & MySQL server-side. I'm not gonna show you my PHP skills, since it has been a while. (..but if you are really curious, please leave a comment, then I can see if I can share some codes). But you will need to request the database schema. With MySQL I could write the following SQL statement: SHOW COLUMNS FROM mytable, where mytable is my database table name. This will return an Array with all my database fields.

The next step is to output JSON. I only care about the field names, and the field types. But... the MySQL data-types are different then the data-types in Ext JS / Sencha Touch, so I somehow need to map a varchar to a string etc. After that's done, my JSON output should look something like this:

{
  success: true,
  fields: [{
    name: "id",
    type: "int"
  },{
    name: "fname",
    type: "string"
  },{
    name: "lname",
    type: "string"
  }]
}

Now we are getting somewhere. These are the fields I dynamically want to inject in my Sencha Model. I can do this with an Ext.Ajax.request. Take a look:

Ext.define('App.store.MyStore', {
  extend: 'Ext.data.Store',
  
  constructor: function(){
      var me = this;
      me.callParent();

      Ext.Ajax.request({
        url: '../data/phpscript/?action=schema',
        success: function(response) {
          try{
            var resp = response.responseText;
            if(resp) {
              var data = Ext.JSON.decode(resp);

              var model = Ext.define("App.model.MyModel", {
                  extend: "Ext.data.Model",
                  fields: data.fields
              });

              me.model = model.$className;
            }
          }catch(e){
            console.error(e);
          }
        },
        failure: function(e){
          console.error(e);
        }
    });
  }
});

Here is what I did. I defined a Store, in the constructor I run an Ajax request, which fetches the fields array from my backend script, (in my case:) ../data/phpscript/?action=schema, which returns the JSON. In the success method, I create a model, and that's where I inject the fields.

Alright. Now hook up the Store to your app and test. You can run in your browser console the following line:

Ext.create('App.model.MyModel', { lname: "Boonstra" });

That should work, it will return the record, and you will see all the (empty) fields that this record contains.

Now that you get the idea, you will be pleased to know, that you can use similar tricks for injecting validations from the server-side or dynamically injecting grid columns... Woot woot.