The future of Sencha’s build tools

Posted on in Cmd Environment ES2015

Sencha Cmd is Java based, and makes use of Apache Ant. You can find all the jar libs when you navigate to the installation folder of Cmd.
For Windows: C:/Documents and Settings/{username}/bin/Sencha/Cmd/{cmd-version}
For Mac OSX: ~/bin/Sencha/Cmd/{cmd-version}

For Ext JS 4, 5 and 6; the best way to develop and kickstart your applications is by running Sencha Cmd from the command line. You can download the latest version here: https://www.sencha.com/products/extjs/cmd-download/
Just run the installer, and make sure the Cmd installation folder is in your class path.
To test if Sencha Cmd is running, run:

sencha which it should output the latest version number.

When you are running an older version of Cmd, you can switch versions via:

sencha switch -list
Which prints an overview of installed Cmd versions.
sencha switch <cmd version>
Which does the actual switch.

Cmd is the tool to:

  • Generate workspaces, applications and code
  • It has a built-in server (Jetty) and file watcher
  • It can load assets (microloader), so you don’t need to manually need to maintain JavaScript or CSS files in your html header.
  • It compiles Sass Themes (previously based on Sass/Compass, now Fashion which is JavaScript based)
  • It concatenate / bundles JavaScripts to single files
  • It compresses and optimizes JavaScript and CSS files
  • It lints your JavaScript code
  • It has support for Apache Cordova / Adobe PhoneGap to make native mobile applications

See also: http://docs.sencha.com/cmd/

During SenchaCon 2016 a few more features get introduced. Which are already available in an early access release. Sencha Cmd 6.5: http://pages.sencha.com/ext-js-tools-ea-2016.html

  • It contains a transpiler, so you can mix ECMAScript 2015 (ES6, ES2015) code within your JavaScript files. (We make use of Google Closure Compiler, and got rid of Rhino)
  • It allows you to create offline applications through the use of service workers (Progressive Web Apps, PWA’s)

Furthermore, Sencha is working on a new build tool alternative with an open toolchain. So it will be possible for you to mix/integrate your own technology (like TypeScript, Grunt, Gulp…) with the tool. This time it won’t be Java based but it’s based on Node JS. It supports the NPM and Yarn package managers, and it has integration with Babel to transpile your ECMAScript 2015, (ES6) code.


In case you missed SenchaCon 2016 in Las Vegas, or it was just too far for you to travel; we are currently organizing SenchaCon Recap Roadshows, in ASIA and in Europe (London (Dec 6th), Paris (Dec 7th) and Munich (Dec 8th): https://www.sencha.com/company/roadshow/
During the roadshows, you will have the chance to learn more and see it all in action!

Beside an introduction and demo of the above build tools, we will also showcase the React and Angular 2 bridges. (to showcase how Angular2/React apps can make use of Sencha components such as grids). We will demo the Sencha Electron package to showcase how you can create native desktop applications with Ext JS and of course we will also preview our own tool suite: Sencha Test 2.0, Visual Studio Code plugin, Sencha Themer 1.1, Sencha Fiddle 2.0.


Sencha sales engineers @SenchaCon Las Vegas

Btw, for the roadshow attendees we have this great deal:

  • Attend the roadshows, and you will get early access to all the SenchaCon video recordings which were made in Las Vegas. (great advanced study material!).

Sencha & ECMAScript 2015

Posted on in ES2015 JavaScript

With just a few more days to go, before the release of Ext JS 6.2, (BTW, Can’t wait! Material Design theme, pinch to zoom, D3 integration, calendar component and much more…) Sencha is already busy with working on the next major version of Ext JS.

We will give you a preview on our long term roadmap on:

es2015

One of the things that’s gonna be huge, is ES2015 support for Ext JS. Our goal is not to rewrite the whole framework according the new ECMAScript standard. no. ..but we want you to be able to write ES2015 code together with your Sencha framework API calls. So you can leverage the advantages of cleaner JavaScript code in your own Sencha classes and controllers.
With that comes new tooling that includes a transpiler, to make sure your code runs in all the supported browsers, and probably will also support for TypeScript, Grunt/Gulp etc. It’s all at an early stage yet, but if you have questions, (and you’re in Europe the week of the 20th of September), you will have the chance to meet the Sencha product manager and engineers at the roadshows.

I will be there as well, presenting an ECMAScript 2015 masterclass. I will cover the top 10 new features of ECMAScript 2015, and teach you what’s new through code examples.

(Are you from the USA? - I will give the presentation at SenchaCon in Las Vegas, November this year.)

Think about:
Block Code Constructs, Arrow functions, Default Parameters, Promises (see also my earlier post: https://www.leeboonstra.com/asynchronous-javascript-promises/), Classes, Modules... etc.

But there’s much more. And unfortunately not everything fits in my Top 10 / in an 45min talk. I like to share with you some more ES2015 code snippets, which are as cool, but didn’t make it in my final presentation. Have a look, this article contains info about:

  • Spread Operators
  • Maps & Sets
  • For Of Loops
  • Generators

Rest parameters & Spread Operator

Let’s say I have a function but I don’t know how many arguments I am gonna pass into it. Maybe 1, maybe 2, or maybe 15. (Not sure if you would want that tho... but you get the idea).

The spread operator looks like this: ...n. 3 dots and a variable which holds an array. That array contains all the parameters that you passed in. The rest parameters.
Let’s have a look how we did this before ES2015 and what’s new:

You can see the ES2015 is much nicer to write. It’s better performing, and it returns a true Array, where the old fashioned JavaScript arguments just contains an object that somehow fakes to be an Array.

You can use the spread operator in combination with Arrays for example:

These new data structures are supported in most of the modern desktop browsers. http://kangax.github.io/compat-table/es6/

New Data Structures

Map & WeakMap

The following four data structures are new in ECMAScript 2015: Map, WeakMap, Set and WeakSet. Let me explain how these work.

Maps are a store for key / value pairs. The Key and value could be a primitives or object references.

ES5 JavaScript was missing a data structure for mapping values. What people use to do; was abusing objects to save values, and that can lead you into nasty inheritance pitfalls. (See: http://speakingjs.com/es5/ch17.html#_pitfalls_using_an_object_as_a_map)

Maps give you a whole bunch of extra functionalities. You can get and set values in a map. You can delete a value in a map. You can loop through entries or values in maps, and you can clear them:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

A WeakMap is a map that doesn’t prevent its keys from being garbage-collected, so you don’t have to worry about memory leaks.

It has almost the same functionalities as a Map, however you can’t iterate over the keys, values or entries and you also can not clear it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (So a String, Number, Boolean, null, undefined or a ES2015 Symbols can not be used as a Weakmap key.). A Map can use primitive values for keys.

w = new Map; 
w.set('a', 'b'); //Map { a: "b" }

w = new WeakMap; 
w.set('a', 'b'); //TypeError: "a" is not a non-null object

Sets and WeakSets

Sets are collections for unique values. The values could be also a primitives or object references.

An ES2015 Set has similar functionalities as a Map. But a value in the Set may only occur once; it is unique in the Set's collection and can not contain duplicates:

var myset = new Set(["A", "A", "B"]);
console.log(myset.size); //2 !!!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Like a WeakMap, WeakSet is a Set that doesn’t prevent its values from being garbage-collected. It has simpler API than WeakMap, because has only three methods:
add(), delete() and has().

These new data structures are supported in most of the modern desktop and mobile browsers. http://kangax.github.io/compat-table/es6/

If you want to use it in production, you will need to make use of a transpiler like Babel, who can provide you a polyfill. (https://babeljs.io)

For-of loop

The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set,String, arguments object etc..):

It is the most concise, direct syntax yet for looping through array elements and it avoids all the pitfalls of for–in loops, (which you would typically use for looping over object properties).Unlike forEach(), it works with break, continue, and return.

As you can see it is pretty similar to for-in loop, which can be used to iterate through object properties.

These new data structures are supported in most of the modern desktop browsers. http://kangax.github.io/compat-table/es6/

Generators

Generators are simply subtypes of Iterators. They are a special kind of function that can be suspended and resumed, which is different compared to iterators.

Generators use function* and yield operators:

Note the yield statements. It returns a generator instance and moves to the next yield when next() is called.

The snippet for the Dice Generator has a while loop that won’t end. It can roll numbers between 1 and 6.

These new data structures are supported in most of the modern desktop browsers. http://kangax.github.io/compat-table/es6/

If you want to use it in production, you will need to make use of a transpiler like Babel, who can provide you a polyfill. (https://babeljs.io)


Want to learn more about ECMAScript 2015? Join me at the roadshows: https://www.sencha.com/company/roadshow
Beside ECMAScript 2015 and TypeScript fun, there will be much to talk about: How to Test your JavaScript code, Build Data analysing apps with Ext JS 6.2, new upcoming Sencha Tools, customer cases and much more...

Asynchronous JavaScript: Promises

Posted on in Ext JS 6 Uncategorized

JavaScript is single threaded, causing code to execute from top to bottom, so two bits of code cannot run at the same time. For example, you might download a JSON file from an (external) server and you’d have to wait until you retrieve that file. Instead of blocking the thread, there are ways you can streamline this code execution by using asynchronous JavaScript.

You’re probably already familiar with asynchronous JavaScript. Events (observer pattern) and Callbacks are examples of asynchronous code. For example, whenever you make an Ext.Ajax request or a user presses a button, the action is pushed into a queue, which is called the event loop. The JavaScript engine doesn’t start processing the event loop until the code has been executed after an async function (from top to bottom). This means that JavaScript code is not multi-threaded even though it appears to be so.

Event Loop

Callbacks are often used when you have an async operation (for example, loading data from a database) that should notify the caller about its completion. When calling such a function, you can pass it another function as an argument, which confirms that something has happened. Putting callbacks into callbacks is a great solution, and I think that’s one of the powerful features of JavaScript. However, it can be messy when your code requires other asynchronous pieces of code first.

For example, you read your user settings from local storage (that’s a callback!). Based on those settings, you make a request from some external server with a database connection, (that’s callback #2). Before you render that information on the screen, you retrieve something else from the database (that’s callback #3).

These steps are very common when you build a large enterprise app. In your code, there will be a callback function, written in a callback function, that’s in another callback function. You can imagine if these functions are spread over separate files that you’d have a hard time reading this code back a month later.

This is where JavaScript Promises comes into play. It’s a new way of writing your code in a more readable and understandable way. A Promise represents the result of a task, which may or may not have been completed. Like a contract for a value that we might not know when the promise is created. It’s an object or function with a then method. Because of the “then” method, the action can be chained endlessly, and that’s awesome!

A Promise typically has one of these 4 states.

  • fulfilled – when the promise succeeds
  • rejected – when the promise failed
  • pending – ongoing, hasn’t been fulfilled or rejected yet
  • settled – it has been fulfilled or rejected already

JavaScript Promises

Promises is part of ECMAScript 6, which is available in the client of some modern browsers, and also within the latest version of Node.js. The following browsers do not support JavaScript Promises: Explorer 11 and below, Android 4.4 and below, and iOS Safari 7.1 and below.

Ext JS 6 supports Promises and conforms to the Promises A+ spec; both Classic and Modern toolkits are included. You can call the Sencha Promises class, which is a wrapper for the native JavaScript functionality. Legacy browsers will use the fallback provided by Sencha, and modern browsers will use the native functionality.

Here’s an example of a function that returns a Sencha Promise object:

requestUserSettings: function(){
        return new Ext.Promise(function (resolve, reject) {
            //something asynchronous, like loading a store
            Ext.getStore(‘Settings’).load({
                callback: function(records, operation, success) {
                        if(success){
                            if(records.length > 0){
                            //when it’s ok
                                resolve(records);
                            } else {
                            //still ok, but no results
                                resolve(false);
                            }
                        } else{
                        //something bad happened
                            reject(operation);
                        }
                  }
            });
        });
}

The Ext.Promise constructor takes one argument, a callback with two parameters, resolve and reject. When it does something asynchronous within the callback, like retrieving user settings from a local storage store, then it calls “resolve”; if everything worked it passes in the result, otherwise it calls “reject” and passes in what went wrong.

Here’s how you use that Promise:

this.requestUserSettings().then(function(records) {
  //It’s ok. do something with the records
}, function(err) {
  //oh no, something went wrong, display a nice error
});

The “then” takes two arguments, a callback for a success case, and another one for the failure case our website. Both are optional, so you can add a callback for the success or failure case only. You can chain as many then methods as you want to run additional async actions one after another.

Besides the “then()” instance method, there are also ways to terminate a Promise chain (“done()”), cancel pending chains (“cancel()”). Also, there’s a way to attach an onCompleted callback to the chain (“always()”), for example with cleanup logic regardless the outcome. And, you can attach an onRejected callback, if one action within the chain is rejected (“otherwise()”), for example to handle failures.

In addition to Ext.Promise, Sencha will also ship Ext.Deferred, which is a mechanism used to create new Promises within Ext JS 6. The difference between these two constructors is that with a deferred constructor the creator has direct access to “behind the scenes” extras, such as progress updates.

Last but not least, Sencha integrated Promises support into Ext.Ajax.

Ext.Ajax.request() is now an instance of a class derived from Ext.data.request.Base which can be used with a then method. It allows you to write code like this:

Ext.Ajax.request({
    url: 'feed.json',
}).then(function(response) {
    // use response
}).always(function() {
   // clean-up logic, regardless the outcome
}).otherwise(function(reason){
   // handle failure
});

More Resources

There’s a lot more information to explain how you can use JavaScript & Ext JS Promises. Take a look at these resources to learn more!