Working at Sencha—Come Join Us

At Sencha, our mission is to create the frameworks and tools that empower developers to create amazing cross-browser app experiences that execute with precision and performance. We have worked hard to assemble a team of brilliant people from around the world, and we periodically bring everyone together for company events.

I recently celebrated my fourth anniversary as a Sencha employee, and I am amazed at how much Sencha has grown during that time. As a remote employee, I don’t often have the opportunity to socialize in person with my friends and colleagues. Although I travel to Sencha HQ (Redwood City, CA) a few times a year for meetings, our company outings have a huge impact on our culture and remind me why I love working here!

In January, Sencha held its annual Worldwide Sales kickoff meeting in the San Francisco Bay Area. The event brought together our Sales, Marketing, Training and Professional Services teams to discuss various corporate and product updates — and although we spent a week in meetings and strategy sessions, we also arranged for a lot of downtime and fun activities.

Sencha Takes Over San Francisco

One of the days we were in town, we stopped our meetings at noon and boarded trolleys for a sightseeing tour of San Francisco. For those of us who work remotely, the trip was our first opportunity to see many parts of the city.

We toured various parts of San Francisco: AT&T Park, Fort Baker and North Beach. We also drove through Chinatown and Pier 39 — and of course, we stopped for some photo ops by the Golden Gate Bridge. Our tour guide was both informative and hilarious as he kept shouting out “points of interest” like the house where Robin Williams filmed the movie Mrs. Doubtfire. We ended up at the North Beach Restaurant for an incredible Italian dinner.

Next Up: SenchaCon 2015

The next major company event for us will be SenchaCon 2015, our annual developer conference hosted in the heart of Silicon Valley. Most of the Sencha team will be in town, and we are really looking forward to socializing with our community and sharing our technical knowledge.

SenchaCon will feature three days of technical sessions and training on JavaScript, HTML5 and Java development in addition to some epic parties. Tickets are still available — find out why I’m excited about SenchaCon and even get a 20% discount code. We hope you’ll join us!

Join Our Team

Sencha currently has a number of open positions across the organization that we need to fill — and we want you to apply.

Come work in a collaborative environment with some of the best people in the industry as we explore and enhance the possibilities of today’s web and mobile technologies. We are building some truly amazing products and need developers with a variety of skills (not just JavaScript).

Sencha offers a fantastic benefits package in combination with competitive salary — and best of all, many positions allow you to work remotely! Come talk to us about joining Sencha.

20120912 Company Update No Comments   Read more

SenchaCon 2015 is Ready to Roll

SenchaCon 2015 is Ready to RollSenchaCon 2015 is April 7-9 and will take place in the heart of Silicon Valley at the Santa Clara Convention Center. The theme of this year’s conference is Design Develop Deploy. We’ll have a day of bootcamps followed by 2 days jam-packed with tech sessions designed to help you get a deeper understanding of the latest tools, techniques and innovations from Sencha. You’ll learn how to design, develop, test, deploy and manage HTML5-based applications more effectively.

Registration is now open! Don’t miss out on this great opportunity to rub elbows with Sencha users from around the globe and see how they use Sencha to drive their business. Sign up now to get super early bird pricing. It’s only available to the first 100 registrants.

SenchaCon 2015 is the place to be to get hands-on training from the experts, see amazing apps that others are building and deploying, have your dev questions answered, and network with the Sencha team as well as other developers. Here’s a sneak peek at what we have planned for you:

  • Pre-conference bootcamps to get you geared up
  • Keynotes that will be sure to get your creative juices flowing
  • Customer presentations that show how using modern web technologies drives business success
  • Tech sessions that are not for the faint of heart

Plus lots of fun — ping pong, pitchers and parties! You won’t want to miss the amazing SenchaCon party we have lined up. Details to follow!

If you develop or manage apps that use Sencha frameworks and tools, you won’t want to miss SenchaCon 2015.

We look forward to seeing you there!

senchacon-teaser.png 3 Comments   Read more

4 Questions to Ask Before Choosing a JavaScript Framework

4 Questions to Ask Before Choosing a JavaScript FrameworkOver the last five years, there has been an explosion of innovation in both web and native technologies. With the rapid release of libraries, frameworks and tools, developers now have many options to create applications for this new world. But, have design patterns and the general utility of micro-library stacks really added productive value to full-scale enterprise web development?

I’ve had the opportunity to interact directly with Sencha enterprise customers over the past several years, and I’m frequently asked how Sencha compares to alternatives in the wider web application development ecosystem. With the evolution of popular (but limited) libraries like AngularJS, Ember and others, developers today have an incredible number of tools to choose from — and often the resulting “solution” is a completely customized stack of multiple, single-purpose, third party libraries.

While these individual libraries and the resulting custom stack have the potential to do some things very well, the unfortunate reality is that a great deal of the functionality must be gathered together from disparate sources, written in-house and require a dedicated team of maintainers in order to meet the demands of enterprise software development.

To learn more, join us for our upcoming webinar.

Analyzing the ROI of JavaScript in Enterprise Software Development

Tuesday, 10/14 at 10:00am PDT

To learn more, join us for our upcoming webinar - Analyzing the ROI of JavaScript in Enterprise Software Development

Sencha has long recognized the power of HTML5, and we have worked hard to create a feature-rich, fully integrated product line focused on developing powerful web applications in the enterprise. As a continually evolving, modern, full-feature JavaScript framework, Ext JS is carefully engineered to meet the most important needs of enterprise web applications — without requiring an assortment of third party add-ons.

Before you start work on your next project, ask yourself these four questions:

  • How can you make your development teams more productive?
  • Can you accurately estimate the development effort involved in making long-lived enterprise applications?
  • Can your developers easily re-use code across the company’s complete application portfolio, regardless of the end-user device or platform?
  • Can you accurately predict the long-term maintenance requirements of an application across its entire lifecycle and potential end-point delivery platforms?

Let’s address each of these questions in detail and examine why the Sencha Ext JS framework is a better choice for building enterprise web applications compared to an arbitrary stack of solutions built on top of third party libraries like AngularJS.

How can you make your development teams more productive?

Every company wants to know how they can help their employees be more productive, and this is particularly true in software development.

One of the most important benefits of HTML5 is that web developers share a common skill set — allowing them to build powerful, interactive applications in a variety of environments. But despite the fact that HTML5 is a common skill set, the reality is that fragmentation exists across the popular libraries and tooling, and it’s difficult to train developers consistently.

Modern Web Stack Criteria

(click to enlarge)

Consider the matrix shown above, which contains all of the different features an enterprise application will likely need. Most popular application libraries, like AngularJS, only implement a small subset of these features — meaning the developer (and by proxy, the enterprise) becomes responsible for pulling together an array of third party software components (and their dependencies) to cover the missing features, unless these features are developed and maintained in-house.

A functionality map showing the broad feature set of Ext JS 5 compared to Angularjs' smaller subset of features

(click to enlarge)

With this approach, it’s also important to consider that each of these third party libraries is independently distributed, each with their own release cycles and “best practices.” Combining many disparate libraries into a single highly-customized application stack often highlights the lack of integration for individual features across the stack, and documentation is also usually incomplete because no two application stacks are exactly the same.

Plus, what happens if you need help? Google might be driving development of AngularJS, but they don’t offer support of any kind, let alone dedicated and timely enterprise support. The same is also true for nearly all of the popular third party JavaScript libraries.

Clearly the challenges companies face with this approach involve:

  • Adequately training their developers across all of the moving pieces
  • Testing the latest releases of all third party dependencies against many internal applications
  • Finding enterprise-level support

This “Rube Goldberg” approach will adversely affect productivity over time, and usually sooner rather than later. The overall efficiency of the development and IT organizations suffers because large development teams are frequently split into two areas of focus: the team doing the updating, documentation and maintenance of the internal custom framework and then the team doing the actual application development that matters to customers or end users.

By contrast, the Sencha Ext JS framework contains nearly all of the features in the matrix. These features are fully integrated across Ext JS, helping your developers design, develop and deploy applications consistently. Our world-class dedicated Training, Support and Professional Services teams also ensure that your organization can get the training and support when needed, giving them the additional resources they need to stay focused and on schedule.

Can you accurately estimate the development effort involved in making long-lived enterprise applications?

It’s no secret that the most common cause of runaway software projects and budgets is poor estimation. A large part of this problem is poorly defined scope, but IT managers also frequently neglect to look at the tools being used to write the software.

No software library or tool is perfect, and it’s certainly unrealistic to expect anyone to know 100% of the tools being used. When you apply that fact across all of the dependencies a project might require, you can easily see how complicated the project estimation matrix becomes.

By applying some simple mathematical formulas, you begin to understand the real-world consequences of having too many dependencies. Assuming every dependency has a 90% reliability factor, and if we treat these dependencies as existing in series, all you need to do is multiply by the number of factors to visualize the overall reliability of the architecture:

(Dependency A = 0.9) x (Dependency B = 0.9) = 0.81 //or 0.9^2
 
(Dependency A = 0.9) x (Dependency B = 0.9) x (Dependency C = 0.9) = 0.729 //or 0.9^3

Although 90% is an average (and perhaps a somewhat arbitrary) metric, the mathematical premise remains intact. You can clearly see how adding more dependencies reduces a system’s reliability exponentially — and that reduction in reliability will translate into problems like delays in delivering features, additional maintenance and testing time, or the need to allocate additional development resources. This directly leads to increased costs and a whole lot of “attention and help” from senior management — something most developers don’t enjoy.

When choosing to build your own framework with AngularJS, your team immediately assumes a number of external dependencies. The customized application stack typically involves AngularJS, jQuery, Bootstrap, Grunt, and others — not counting any code developed and maintained in-house. While this might be fine for smaller projects and teams building relatively straight-forward applications and websites, the potential risks and consequences become very pronounced in the enterprise, where teams are larger, geographically diverse, and maintain a large code base common to many applications.

A full-featured framework, such as Ext JS, has fewer development dependencies because the framework simply contains more functionality, eliminating the need for most third party libraries. But the factors of reliability even go beyond the number of dependencies — because Ext JS contains more functionality, that functionality is inherently more reliable because each feature is guaranteed to be compatible across the framework. With fewer required points for third party integration, it’s easy to see how estimating future development is less complicated by using a full-featured framework.

Can your developers easily re-use code across the company’s application portfolio, regardless of the end-user device or platform?

There are two popular acronyms often used in software development: DRY (Don’t Repeat Yourself) and KISS (Keep It Simple, Stupid). And while most developers and application managers understand those terms, it’s also clear that not everyone follows this advice.

For example, most senior developers understand how to extract common code patterns into a higher-level abstraction to be used in multiple places — and therefore the problem of re-use at the small scale is pretty well solved. But what happens in the enterprise, where an organization may have very large software teams managing many applications across a variety of devices and platforms?

The reality of software development in the enterprise is that large-scale code re-use is mostly an unsolved problem. Modification of re-used code is particularly error-prone in these situations, so the “third party library” approach to application development really begins to cause issues as individual modules, developed by different teams with uncoordinated release cycles, need to be updated or replaced.

Ext JS solves this problem by applying a standard application development process, organizing the code itself and providing a consistent methodology. Combining Ext JS with Sencha Cmd, the fully integrated Sencha product line makes it simple to share code across teams and applications.

Can you predict the long-term maintenance requirements of an application across its entire lifecycle and potential end-point delivery platforms?

It has been said that software maintenance is largely about adding new capability to old software — not necessarily fixing bugs. In fact, maintaining existing applications typically consumes between 40 and 80 percent of software costs.

Enterprise software often is designed to stay in production for as long as five to ten years — sometimes longer. Consider that most of the popular JavaScript libraries are only targeting “modern browsers.” Keep in mind that older browsers (namely IE8) still maintain a sizeable chunk of the desktop browser market share, and yet AngularJS and other libraries have completely dropped support for it.

With those sorts of numbers, it’s absolutely critical that development teams actually understand the tools used to build the product. If simply reading and comprehending the existing code consumes as much as 30 percent of the total maintenance time, you can conclude that application maintenance is more difficult than the initial development. This problem only gets worse when the teams maintaining applications inevitably change over time, and the constant influx of new developers results in additional confusion.

Because all Sencha applications follow the same design patterns and methodology, any developer on the team can handle both new development as well as maintenance of legacy software. Ext JS also supports legacy browsers (including IE8) in addition to the latest “modern” versions, so your applications are guaranteed to work for years to come with no additional worry.

Conclusion

Popular JavaScript libraries like AngularJS certainly have their place in the world of web development. The incredible growth of permissive open source code has enabled HTML5 to explode as an application delivery platform and secured its future as a critical web technology. But the enterprise has very specific, long-term needs that are simply not addressed by ad hoc assemblies of disparate micro-frameworks gathered from uncoordinated sources.

Ext JS is clearly positioned to address these concerns, and does so through a robust and tightly integrated set of features. Download the free 30-day trial and see for yourself how building powerful enterprise web applications is easier with Ext JS.

Want to learn more? Join us for our upcoming webinar.

Analyzing the ROI of JavaScript in Enterprise Software Development

Tuesday, 10/14 at 10:00am PDT

To learn more, join us for our upcoming webinar - Analyzing the ROI of JavaScript in Enterprise Software Development

Additional Resources

This blog post specifically compared Ext JS to AngularJS, but Sencha has compiled a much deeper analysis of Ext JS to other JavaScript libraries. For more information, please read our recent whitepapers:

analyzing-the-roi-of-javascript-in-enterprise-software-development-1.png 11 Comments   Read more

Create Custom Charts using Sencha Charts

Guest Blog Post

Overview

With the launch of Ext JS 5, Sencha introduced a new and more powerful Sencha Charts package, which has built-in support for touch events. This means you can use touch gestures to interact with the charts. Sencha Charts was built with performance in mind and will render charts as SVG or HTML5 Canvas, where appropriate, (or VML in IE8). You can refer to Ext JS 5 Charts Kitchen Sink to test drive and learn more about Sencha Charts.

In this article, you will learn how to create custom charts using the new Sencha Charts package. We’ll demonstrate how to create a new financial chart with William %R indicator.

This article assumes that you have a prior understanding of Sencha Charts architecture. You can refer to the following articles to understand the architecture and also get a walkthrough of an existing chart implementation:

Creating a New Financial Chart

In this section, you will see how to create a custom stock chart – William %R – that is a momentum oscillator measuring the level of the close relative to the high-low range over a given period of time. This is also called “look-back period”.

What’s the Chart All About?

Based on the data, the following data needs to be calculated based on the look-back period:

  • Highest-high for the period
  • Lowest-low for the period

Once the above values have been calculated, the %R value will be calculated for a record by applying the following formula:

%R = (Highest High - Close)/(Highest High - Lowest Low) * -100

After the %R values have been calculated, we need to draw a chart between %R value and the time, as shown below in a sample William %R chart:


Credit: StockCharts.com

Technically, to create a William %R chart, we would consider the following requirements as the scope for this article:

  1. It takes the following parameters:
    1. oversoldLevel – this is typically set to -80. However, it needs to be configurable
    2. overboughtLevel – this is typically set to -20. However, it needs to be configurable
    3. lookbackPeriod – this is typically set to 14 days. However, it needs to be configurable
  2. It draws a numeric axis with -100 as minimum and 0 as maximum values
  3. The numeric axis indicates the following marks:
    1. -80 – oversoldLevel
    2. -20 – overboughtLevel
    3. -50 – middle
  4. Horizontal lines are drawn at the following levels:
    1. -80 – oversoldLevel – continuous line
    2. -20 – overboughtLevel – continuous line
    3. -50 – middle – dotted line
  5. The area above the overboughtLevel and below oversoldLevel need to be filled
  6. The chart will be created based on Sencha Charts package architecture.

For brevity, I have excluded axis, legend, marker, tooltip, and theme customization.

Let’s Structure It

The diagram below shows the specific classes that we need to implement to create William %R chart and how they are connected with Sencha Charts classes:

Time to Get Our Hands Dirty — Implementation Steps and Code

With the high-level requirements and design in place, let’s start the implementation.

CustomSenchaCharts.sprite.WilliamPctR

This class implements the William %R sprite logic to draw the lines at -80, -50, and -20 levels. Also, it takes care of filling the areas above -20 and below -80 levels. These levels are configurable, and they are passed as part of the series configuration.

In this class, we have three important methods:

  • drawOverBought – draws and fills the area above overboughtLevel, i.e. -20
  • drawOverSold – draws and fills the area above oversoldLevel, i.e. -80
  • renderAggregates – main method that draws the lines at -80, -50, -20 levels, also calls drawOverBought and drawOverSold methods to draw and fill the overbought and oversold areas, and, finally, draws the series line with the passed stroke style
drawOverBought

This method detects the overbought area, draws it and fills it with the specified stroke style. When the beginning of overbought area is detected, we use the method below to find out the coordinate of the point where y=-20 line intersects the line segment drawn between the points on either side of it:

Similarly, logic is followed to detect the end of the area and calculate the coordinate of the point that lies on y=-20.

Following, is the complete implementation of the method:

        drawOverBought: function (surface, ctx, start, end, list, xAxis, obLevel) {
                var attr = this.attr,
                        i, x, y, x0, y0, obx = 0, oby = obLevel, obStart = false, obEnd = false;
 
                var lbPeriod = attr.lookBackPeriod - 1;
 
                x0 = list[0];
                y0 = list[1];
 
                var tx = x0, ty = y0;
 
                for (i = 3 * lbPeriod; i < list.length; i += 3) {
                        x = list&#91;i&#93;;
                        y = list[i + 1];
 
                        //detect if the ob starts
                        if (ty <= y && ty <= oby && y >= oby) {
 
                                //find the x co-ordintate of the point of intersection
                                obx = x - (((y-oby)*(x-tx))/(y-ty));
 
                                //start drawing the path
                                ctx.beginPath();
                                ctx.moveTo(obx, oby);
 
                                obStart = true;
                                obEnd = false;
                        }
 
                        //detect if the ob ends
                        if (ty >= y && ty >= oby && y <= oby) {
                                obx = tx + (((x-tx)*(ty-oby))/(ty-y));
                                ctx.lineTo(obx, oby);
 
                                ctx.closePath();
                                ctx.fill();
 
                                obStart = false;
                                obEnd = true;
                        } 
 
                        //keep drawing the line
                        if (y >= oby) {
                                //if start was not detected - open start
                                if (!obStart) {
                                        ctx.beginPath();
                                        ctx.moveTo(x0, oby);
                                        ctx.lineTo(x0, y0); 
 
                                        obStart = true;                   
                                }
 
                                ctx.lineTo(x, y);
                        }
 
                        tx = x, ty = y;
                }
 
                //if end is not detected
                if (!obEnd) {
                        ctx.lineTo(x, oby);
                        ctx.closePath();
                        ctx.fill();
                }
        }
drawOverSold

This methods, logically, works similarly to the drawOverBought method where it draws and fills the oversold area with the specified stroke style.

drawOverSold: function (surface, ctx, start, end, list, xAxis, osLevel) {
                var attr = this.attr,
                        i, x, y, x0, y0, osx = 0, osStart = false, osEnd = false, osy = osLevel;
 
                var lbPeriod = attr.lookBackPeriod - 1;
 
                x0 = list[0];
                y0 = list[1];
 
                var tx = x0, ty = y0;
 
                for (i = 3 * lbPeriod; i < list.length; i += 3) {
                        x = list[i];
                        y = list[i + 1];
 
                        //detect if the os starts
                        if (ty >= y && ty >= osy && y <= osy) {
 
                                //find the x co-ordintate of the point of intersection
                                osx = tx + (((x-tx)*(ty-osy))/(ty-y));
 
                                ctx.beginPath();
                                ctx.moveTo(osx, osy);
 
                                osStart = true;
                                osEnd = false;
                        }
 
                        //detect if the os ends
                        if (ty <= y && ty <= osy && y >= osy) {
                                osx = x - (((y-osy)*(x-tx))/(y-ty));
                                ctx.lineTo(osx, osy);
 
                                ctx.closePath();
                                ctx.fill();
                                osStart = false;
                                osEnd = true;
                        } 
 
                        //keep drawing the line
                        if (y <= osy) {
                                //if start was not detected - open start
                                if (!osStart) {
                                        ctx.beginPath();
                                        ctx.moveTo(x, osy);
                                        ctx.lineTo(x, y); 
 
                                        osStart = true;                   
                                }
 
                                ctx.lineTo(x, y);
                        }
 
                        tx = x, ty = y;
                }
 
                //if end is not detected
                if (!osEnd) {
                        // console.log('closing!!');
                        ctx.lineTo(x, osy);
                        ctx.closePath();
                        ctx.fill();
                }
        }
renderAggregates

This method is called during the rendering of the series, and it takes care of drawing all the sprites for a series. We need to override this method, so we can:

  • draw horizontal lines at -80, -50, and -20 levels
  • draw line series
  • draw and fill overbought and oversold areas

To render the sprites for William %R, first, we transform the overboughtLevel and oversoldLevel to the co-ordinate system that the framework uses:

                var obLevel = attr.overboughtLevel * yy + dy;
                var osLevel = attr.oversoldLevel * yy + dy;
                var midLevel = -50 * yy + dy;

ctx contains the reference to the underlying rendering engine — Canvas or SVG.

After the coordinates have been transformed, we draw the horizontal lines — solid for -80 and -20 and dashed for -50:

                //Draw overbought, oversold and -50 mark lines
                me.drawYLine(ctx, xLen, obLevel);
                me.drawYLine(ctx, xLen, osLevel);
                me.drawYLine(ctx, xLen, midLevel, true);

Then, we call the drawOverSold and drawOverbought methods to draw and fill the areas by passing the transformed values to them:

                //Draw oversold areas
                me.drawOverSold(ctx, list, osLevel);
 
                //Draw overbaught areas
                me.drawOverBought(ctx, list, obLevel);

Finally, we draw the path with a stroke by calling drawStroke, which is an existing method on Ext.chart.series.sprite.Line class:

                //draw stroke
                me.drawStroke(surface, ctx, start, end, list, rect[1] - pixel);
                ctx.stroke();

drawYLine

A private method that draws a horizontal line — dashed or solid — for the given y.

        drawYLine: function(ctx, length, y, dashed) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(length, y);
                ctx.closePath();
 
                var linedash;
                if (dashed) {
                     if (ctx.getLineDash) {
                         lineDash = ctx.getLineDash();
                         ctx.setLineDash([3]);
                     } else {
                         lineDash = ctx.lineDash;
                         ctx.lineDash = [3];
                    }
                }
             ctx.stroke();
             if (dashed) {
                     if (ctx.setLineDash) {
                             ctx.setLineDash(lineDash);
                     } else {
                         ctx.lineDash = lineDash;
                    }
                }

Now, with the sprite class in place, let’s move on to our next class — CustomSenchaCharts.series.WilliamPctR — where we will implement the series related logic.

CustomSenchaCharts.series.WilliamPctR

The series class accepts the store and following specific parameters:

  • overboughtLevel
  • oversoldLevel
  • lookBackPeriod

The store contains the low, high and close fields that this series class uses to calculate the %R value based on the lookBackPeriod — defaults to 14 days.

The following constructor code calculates %R and sets it on the records on the passed store:

        constructor: function (config) {
 
                var me = this;
 
                var st = Ext.data.StoreManager.lookup(config.store);
                var recs = st.getRange();
                var highs = Ext.Array.pluck(Ext.Array.pluck(recs, "data"), config.highField);
                var lows = Ext.Array.pluck(Ext.Array.pluck(recs, "data"), config.lowField);
 
                var lpPeriod = config.lookBackPeriod - 1;
 
                st.each(function (item, index, length) {
                        if (index < lpPeriod) {
                                item["pctr"] = "";
                                return;
                        }
 
                        //get highest high of last 14 days
                        var maxHigh = Ext.Array.max(Ext.Array.slice(highs, index - lpPeriod, index + 1));
 
                        //get lowest low of last 14 days
                        var minHigh = Ext.Array.min(Ext.Array.slice(lows, index - lpPeriod, index + 1));
 
                        //calculate %R and set it on the record
                        var pctr = ((maxHigh - item.data[config.closeField])/(maxHigh - minHigh)) * -100
                        item.data.pctr = pctr;
                });
 
                this.callParent(arguments);
        }

Now that we have updated the records with their %R value, there is one more method that we need to implement — actually, override — which is called at the time of rendering the WilliamPctR sprite to get the configuration for the sprite. We need to implement it, so we can pass the overboughtLevel, oversoldLevel, and lookBackPeriod parameters to the sprite, which it uses to draw and fill different sprites:

        getDefaultSpriteConfig: function () {
                var me = this,
                        parentStyleConfig = me.callParent(arguments);
 
                return Ext.apply(parentStyleConfig, {
                        overboughtLevel: me.config.overboughtLevel,
                        oversoldLevel: me.config.oversoldLevel,
                        lookBackPeriod: me.config.lookBackPeriod
                });
        }

Now, we are left with one last class — CustomSenchaCharts.chart.WilliamPctR — the chart that lets us create a William %R chart in an application.

CustomSenchaCharts.chart.WilliamPctR

The chart class extends the CartesianChart, where it expects a numeric type axis to be specified by the caller. It uses the specified numeric axis to draw the %R values. The class sets the following William %R related additional axis configs in its iinitConfig method, which is called at the time on the class initialization:

  • fields – the field that would be rendered on the numeric axis; it is set to ‘pctr’ – %R
  • minimum – minimum value to be shown on the axis; it is set to -100
  • maximum – maximum value to be shown on the axis; it is set to 0 as %R oscillates between 0 and -100
Ext.define("CustomSenchaCharts.chart.WilliamPctR", {
        extend: 'Ext.chart.CartesianChart',
        requires: ['CustomSenchaCharts.series.WilliamPctR', 'CustomSenchaCharts.sprite.WilliamPctR'],
        xtype: 'williampctrchart',
 
        initConfig: function(config) {
 
                var series = config.series[0];
                var obLevel = series.overboughtLevel;
                var osLevel = series.oversoldLevel;
 
                Ext.Array.each(config.axes, function(axis, index, recs) {
                        if (axis.type === 'numeric') {
                                Ext.apply(axis, {
                                        fields: ['pctr'],
                                        maximum: 0,
                                        minimum: -100,
                                        renderer: function (value, layoutContext, lastValue) {
                                                if (value == osLevel || value == -50 || value == obLevel){
                                                        return value;
                                                } else {
                                                        return "";
                                                }
                                        }
                                });
                        }
                });
 
                this.callParent(arguments);
        }
});

We’re almost done except for one final step where we will use the above chart in an application and see it in action.

See it in Action

In the previous section, we defined a WilliamPctR chart with ‘williampctrchart’ xtype. Let’s see how we can use it in our sample application.

To use the above chart in an application, we can either instantiate it using Ext.create call or use the xtype. For example, here is the code showing the configuration to add this chart to an Ext JS container as one of its items:

{
                                xclass: 'CustomSenchaCharts.chart.WilliamPctR',
                                height: 250,
                                docked: 'bottom',
                                insetPadding: 0,
                                background: 'white',
                                series: [
                                        {
                                                store: 'Apple',
                                                type: 'williampctr',
                                                xField: 'date',
                                                yField: 'pctr',
                                                highField: "high",
                                                lowField: "low",
                                                closeField: "close",
                                                overboughtLevel: -20,
                                                oversoldLevel: -80,
                                                lookBackPeriod: 14,  //in days
                                                style: {
                                                        stroke: 'rgba(237,123,43,0.75)',
                                                        fill: 'rgba(237,123,43,0.1)',
                                                        miterLimit: 1
                                                }
                                        }
                                ],
                                axes: [
                                        {
                                                type: 'numeric',
                                                position: 'left',
                                                style: {
                                                        axisLine: false
                                                }
                                        },
                                        {
                                                type: 'time',
                                                position: 'bottom',
                                                fields: ['date'],
                                                style: {
                                                        strokeStyle: '#666',
                                                        estStepSize: 150
                                                },
                                                dateFormat: 'Y',
                                                segmenter: {
                                                        type: 'time',
                                                        step: {
                                                                unit: 'y',
                                                                step: 1
                                                        }
                                                },
                                                label: {
                                                        fontSize: 10,
                                                        fillStyle: '#666'
                                                }
                                        }
                                ]
                        }

The following shows the William %R output:

You may download the complete code from GitHub. Note: this code was written using the current version of Ext JS (5.0.1).

Summary

In this article, we discussed how to create a custom stock chart based on the Cartesian coordinate system by implementing a custom chart, series and a sprite. We then saw how to use the custom stock chart in an Ext JS 5 application. We hope this article has helped you understand the overall structure of the Sencha Charts package, important classes, their responsibilities, interactions and how you can create a custom chart.

References

sencha-charts.png No Comments   Read more

A Fond Farewell to YUI

Farewell to YUILast week, Yahoo announced they are immediately stopping all new development on their Yahoo User Interface (YUI) library. There are tens of thousands of YUI developers that have written millions of lines of code that are probably sad to have read this, but I am sure they also understand the rapidly evolving web development environment that led to this decision. The Sencha Ext JS framework and YUI have a kinship and a long history together, so we wanted to take this opportunity to reflect on our past and discuss what the future holds.

A Brief History of YUI and Ext JS

In the early-to-mid 2000s, the world of web development looked very different than it does today. Internet Explorer 6.0 ruled most desktop computers, but early versions of Firefox, Safari, and other web browsers were emerging and becoming more and more popular. Internet connections were relatively slow, websites very basic and few people thought about interactive ”web applications.“ HTML5, Google Chrome and the iPhone didn’t yet exist.

With the birth of JavaScript libraries like Prototype and jQuery in 2005-2006, web developers could spend less time worrying about the many cross-browser quirks and began to embrace JavaScript for more than simple web form validation and image rollovers.

YUI was first conceived in 2005 and made public in early 2006. YUI became very popular very quickly, not only because it was attached to the name ”Yahoo“ (giving it immediate credibility) but also because it was among the very first JavaScript widget libraries. Developers now had the power to create customizable widgets that worked consistently across browsers — allowing web applications to duplicate much of the functionality of ”native desktop“ applications.

Not long after YUI was released, yui-ext was created, a library of extensions which became the precursor to Sencha’s Ext JS 1.0.

Ext JS Has YUI Roots, But We Took a Different Path

Ext JS 1.0 was first released as a standalone framework in 2007, removing its YUI dependencies. However, wanting to remain true to our YUI roots while offering the most robust development framework to our customers, Sencha continued to ship optional ”adapters“ for YUI with Ext JS as late as version 3.x.

The programming paradigms still used today in Ext JS and Sencha Touch are directly influenced by our history with YUI. YUI was revolutionary when it was first released, being one of the only JavaScript libraries to embrace an object-oriented focus for building applications. The Sencha class system in both Ext JS and Sencha Touch directly reflects this history. Other areas of the Ext JS framework such as our drag-and-drop capabilities, still bear YUI’s influence.

But while Ext JS and YUI have a shared history and similar paradigms, Sencha firmly believed then, and still believes today, that our destinies were and are very different. Our strategy at Sencha is to continuously modernize our framework and update our platforms with the latest features and functionality to improve the productivity of large enterprise development teams.

The Future of Enterprise Web Applications

Yahoo’s recent announcement explained their rationale for decommissioning YUI:

…it has become clear to us that the industry is now headed in a new direction… JavaScript is now more ubiquitous than ever. The emergence of Node.JS has allowed JavaScript to be used on the server side… New package managers (npm, bower) have spurred the rise of an ecosystem of third party, open source, single-purpose tools… New application frameworks (Backbone, React, Ember, Polymer, Angular, etc.) have helped architect web applications in a more scalable and maintainable way…

The consequence of this evolution in web technologies is that large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

Most of these things are true, and in many ways they’re great for the Web. JavaScript is being used everywhere, and every day we see new and exciting projects being created. HTML5 is more powerful and promising than ever before.

However, the simple fact that so many new, disparate and unconnected libraries have emerged recently is very telling. The pendulum in web development might be swinging towards lightweight libraries as good starting points, but clearly there is disagreement about even a minimum set of critical/necessary end-to-end development features and the ”best“ way to implement them.

The Modern Web Stack

When we talk to many of our customers and partners, we consistently hear that the third party JavaScript stack is problematic in the enterprise. For certain kinds of application experiences (e.g. a pure content application that targets modern browsers, written and maintained by a solo developer) the answer may be that no framework is needed at all. On the other hand, for a portfolio of complex and interdependent enterprise apps developed by large, dynamic and geographically dispersed teams, the answer may be to adopt a single, standards-based framework across the organization.

AngularJS is beginning to emerge as one of the most popular JavaScript libraries today — and while it is a great library, you must keep in mind that it is relatively incomplete if you are trying to deliver a large portfolio of enterprise-grade applications (see chart below). Its own website boasts that ”AngularJS is a toolset for building the framework most suited to your application development,“ so enterprise developers must assemble the rest of the required functionality from various third parties.

While this certainly provides the most customized solution, there are also a number of significant short-term and long-term issues with this strategy. Without a common architecture or coding style, testing and maintaining the stack becomes difficult as the homegrown ”framework“ grows over time. Each independent library can bring a subtly different interpretation of ostensibly similar functionality. And most importantly, the development team will face multiple release cycles that are unsynchronized with each other — not to mention the risk that a vital piece of the stack will be abandoned by its maintainer.

These are the significant (and clearly known) business risks for enterprise development managers and CIOs to consider when selecting a provider with fickle interests. Or, when assessing the myriad of new micro-frameworks that might attract the attention of individual developers who may not be aware of downstream maintenance costs.

As an alternative, Sencha provides a much more comprehensive framework (see chart below). The Sencha Ext JS framework offers a very broad selection of basic and compound widgets (over 150), a high-level visualization package as well as a lower-level drawing API; a rich package of containers and themes, and a well-thought-out view system. Our framework also offers an architectural package for MVVM and MVC, ARIA support, RTL support and more, all with a single coding style.

All of these capabilities are engineered and tested to work together, professionally maintained and updated in a synchronized fashion. In addition, the Sencha offerings are backed by a flexible set of Training packages, a dedicated Tech Support team and a deeply experienced Professional Services organization.

Sencha believes that the cohesiveness of unified frameworks like Ext JS provide greater value to enterprise development teams than an aggregation of disparate multiple third party libraries — but we also acknowledge that no framework or library is perfect for every project or every organization. For a more thorough analysis of challenges faced by web application developers, please download our whitepaper: The Modern Web Stack: A taxonomy of front-end technologies as an aid to decision making.

Looking into the Future

Given our long history with YUI, we are certainly sad to see an old friend go. We remain more convinced than ever that feature-rich, enterprise-focused frameworks, such as Ext JS and Sencha Touch, are the best tools to help enterprises effectively and efficiently deliver powerful, long-lived web applications that extend across desktop, tablet and smartphone platforms.

Sencha is fully committed to HTML5, and we are more excited than ever about the future of the Web. Ext JS 5 was a huge step forward for our framework, and we continue to see significant growth in our user community and customer base. More than 60% of the Fortune 100 now use our products, solidifying Sencha as the top choice for building business-focused enterprise applications with web technology. If you’re new to Sencha, you can download a 45-day free trial of Ext JS.

Looking towards the future, Sencha has many more ideas that will dramatically enhance how organizations design, develop, test, deploy, and manage their critical business applications. Sencha Space, our application deployment and management solution is an advanced platform for securely deploying mobile apps and delivering a consistent user experience. Users can launch any mobile web app or HTML5 app in a secure, managed environment. We look forward to presenting all of these ideas to you and more at our upcoming SenchaCon in April 2015.

So, a fond and final farewell to our good friend YUI — we understand and will not forget the significant role played in accelerating the capabilities of Web-based application development technologies.

yui-teaser.png 5 Comments   Read more

The Downside of Native Packaging

The 2007 introduction of the iPhone ushered in a new era of mobility. We now expect our applications and data to be accessible on the most convenient network-connected device. Our appetite for mobile technology has resulted in a massive influx of mobile devices supporting a myriad of different mobile operating systems.

Many application developers soon realized the inefficiency of developing native applications in this multi-device, multi-platform world. They chose instead to embrace web technology and the emerging open standards around HTML5. The shift, now called hybrid app development, created the need for a tool to package these HTML5-based applications, run them on the device, and provide access to common device hardware features like the camera, GPS, and accelerometer.

Starting in 2009, native packaging solutions were created to address this need. Developers have lauded native packagers for allowing HTML5-based apps to fit into the still-dominant public app store distribution model. More importantly native packagers meet a number of important needs for consumer applications and have enabled many HTML5 developers to access app store distribution who otherwise would not have had such an opportunity. Yet in subsequent years, the many deficiencies of native packagers have become painfully obvious to many application developers in the enterprise.

These deficiencies include:

  • Security – Sensitive data is stored unencrypted in the packagers’ caches and data stores
  • Complex app lifecycle – You have to build for multiple platforms and manage the deployment and maintenance of those binaries over the life of the application
  • Subject to frequent mobile OS changes – Any changes or backward-incompatibility from a mobile device vendor can break your packaged app
  • App Store Distribution – Distributing enterprise applications through consumer app stores is highly inefficient.

It’s now 2014; organizations have been dealing with this pain for long enough. They want a long-term solution for application and data mobility. The answer is to deploy HTML5 apps directly into a secure, managed runtime environment. This type of solution has many benefits:

  • End-users get a superior application user experience, relief from app fatigue, and protection for personal privacy. Their applications are always up to date.
  • Developers reap the benefits of both the web and today’s mobile devices. They no longer have to package the app for multiple platforms. They can also eliminate the hassle of dealing with consumer app stores to distribute their apps.
  • Organizations can instantly secure and manage the lifecycle of their apps, data, and users, fighting app sprawl in the process. Administrators can grant and revoke user access to apps and data as business needs dictate, wiping business data from users’ devices without touching personal data. Furthermore, their data is encrypted on the device, protecting them from data breach.

Native packagers have served you well at a time when you really needed it. But if these points concern your organization at all, there is a better way to solve these problems now. If you’re making apps for the enterprise, it’s time to let native packagers go.

Click here to learn more about how Sencha can ease your transition to a post-native packager world.

20140414-mind-the-phone-gap-teaser-v1.jpg 3 Comments   Read more

Top Support Tips: August 2013

Ready, Aim, Sass

Let’s say you have built your application, but your SCSS has changed. There is no need to sit through the entire build process again. Instead, why not target the exact part of the build that you need?

All you have to do is execute the following command.

sencha ant sass
	

This will make your build process begin with compiling your Sass instead of making you recompile other parts of your application that may not need attention. You can find a full set of target points with this command.

sencha ant .help
	

NOTE: Your application must be built before targeting specific points in the build process.

For more information about Ant integration, you can check out our docs:
http://docs.sencha.com/extjs/4.2.1/#!/guide/command_ant


Getting the Best Layout When Using Ext.Img

Co-author: Seth Lemmons

Oftentimes, users need to use a layout containing Ext.Img instances. The Image’s resources will load after the Ext JS layout of the parent container has run. If a specific height/width is not passed into the component’s configuration, the Image will render after the image has been laid out with the image’s actual dimensions being considered.

To ensure proper layout, it is recommended that users provide a height and width for all Image configs.

That said, applications may not always “know” the image dimensions and therefore, they must be determined after the image resource is loaded. To accommodate these instances, you can extend Ext.Img and make further use of the onRender method. For instance, you can have the Image’s element (Image.getEl()) listen for the ‘load’ event. Then, onLoad, check for the Image’s ownerCt property. If it exists, do Image.ownerCt.updateLayout(). This will force the parent container to recalculate the layout for the child items using the image’s actual dimensions.

Please note: this is still extra computation and should only be considered when an Image’s explicit height and width are unknown.

EXAMPLE:

	Ext.define('MyApp.view.MyImage', {
	    extend: 'Ext.Img',
	    alias: 'widget.myimage',
	    onRender: function () {
	        var me = this;
	        me.mon(me.getEl(), 'load', me.onImgLoad, me);
	        me.callParent(arguments);
	    },
	    onImgLoad: function () {
	        var me = this,
	            owner = this.ownerCt;
	        if (owner &amp;&amp; (!me.height || !me.width)) {
	            owner.updateLayout();
	        }
	    }
	});
 
	var testImage = Ext.widget('myimage', {
	    src: 'http://www.sencha.com/img/sencha-large.png',
	    // PROVIDE THE SOURCE IMAGE DIMENSIONS TO AVOID UNNECESSARY LAYOUTS WHICH CAN AFFECT PERFORMANCE
	    // height: 140, width: 372
	});
 
	Ext.widget('toolbar', {
	    renderTo: document.body,
	    items: [testImage, {
	        text: 'Button'
	    }]
	});

For more information about Ext.Img, please see our docs here:
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Img.


Setting the Best Build Path in Sencha Touch

The Sencha Touch default build location may not always be ideal for every user’s dev environment. Sencha Cmd currently looks for a build destination in multiple locations so changing from the default build location isn’t always simple. That said, config options passed in via command line always win out over file settings.

To modify your Sencha Touch build location, simply add the build location to your properties at build time like this:

sencha config -prop args.destination=/path/to/build/dir then app build
	

For more information about build options, please check out our docs here:
http://docs.sencha.com/touch/2.2.1/#!/guide/command_advanced.

No Comments   Read more

Toward Modern Web Apps with ECMAScript 6

ECMAScript, the official name for the language we all know as JavaScript, has enjoyed tremendous success over the last couple of years. With convergent standard support, performance boosts from modern JavaScript engines, as well as its foray into the server-side stack, ECMAScript has gained significant traction and redefined the scope of HTML5 applications. The final requirement for world domination is the modernization of its syntax and run-time, which is coming in ECMAScript 6 and is the subject of this post.

To understand the language progress within ECMAScript 6, first we need to understand how it is developed. The official ECMAScript specification, also known as ECMA-262, is defined by a standard body called Ecma International. The TC39 group within ECMA is responsible for formalizing the language specification (TC stands for Technical Committee). Every browser vendor, as well as other interested parties, has one or more representative members in this committee. Those members are tasked with championing features and additions to the next version of the language. From time to time, TC39 members meet to review the recent progress and to finalize the formal specification. Often, ideas are also discussed with the public in the es-discuss mailing-list.

The ECMAScript 6 specification is still in the draft stage. There have been many draft revisions so far, with the latest one coming out as recently as July 15th. Keep in mind that the concepts and the examples illustrated in this article follow the latest specification draft and its related discussions at the time of writing, but there is still always a possibility that some syntax or function name may change in the near future before the finalization of the specification.

“I Can See Clearly Now”

It is often said that “Code is written once but read many times”. In fact, many of us who spend countless hours in the code review process realize how important it is to have clear and unambiguous code. In addition, crystal clear syntax makes it easy for a new team member to understand the code and to avoid common pitfalls.

A common mystery for a novice is the following construct:

	// ES 5
	function inc(x, y) {
	  y = y || 1;
	  return x + y;
	}

The use of the second argument, y, can be confusing. Its value includes a logical OR with the constant 1, so that if y is undefined (or, more precisely, when y is false), it has the value of the constant 1. For example, if the function is called with only one argument, such as inc(4), the return value is 5 (which is 4 plus the default value of 1 for y). Such a seemingly clever hack is buggy (passing y as 0 produces the wrong outcome), error-prone (what happens if bitwise OR is accidently used instead of logical OR?), and totally meaningless to those who are not familiar with the technique. There are other variants which solve these issues, but the problem remains the same: it is still a run-time workaround.

ECMAScript 6 solves this issue by having a built-in feature for the default parameter value, allowing the previous construct to be rewritten in the following way, which should make a lot of sense to those familiar with other programming languages:

	// ES 6
	function inc(x, y = 1) { return x += y; }

Another common pitfall for beginners is the fact that variables have function scope instead of block scope. If someone is already used to other “curly-brace” programming languages, this scope difference can come as a shock. In addition to that, variable hoisting confuses the situation even further: a variable may exist in a scope although it has not been initialized.

Take a look at the following example where the variable N within the conditional body shadows the outer N. Since N is function-scoped, declaring a new N within the body of the if statement does not have any effect; it is still the same N and thus the original value is overwritten.

	// ES 5
	function doSomething() {
	  var N = 5;
	  if (someCondition) {
	     var N = 10;
	     doSomethingElse(N);
	  }
	  console.log(N); // 10
	}

This is a rather trivial example and hence the problem can be spotted immediately. But in a large code block which uses several closures, such a sloppy name conflict may lead to obscure bugs.

ECMAScript 6 introduces the concept of lexical block scope, where a variable or a function is enclosed within the closest curly braces. The problem in the above example can be solved elegantly using the new let keyword.

	// ES 6
	function doSomething() {
	  let N = 5;
	  if (someCondition) {
	     let N = 10;
	     doSomethingElse(N);
	  }
	  console.log(N); // 5
	}

A sibling to let is const. It works the same as let, including the block scope, but it requires an initialization value. As the name implies, const has a constant binding and thus replacing its value has no effect:

	// ES 6
	const limit = 100;
	limit = 200;
	console.log(limit);  // 100

The major use case for const is to safeguard important constants from being overwritten accidentally.

ECMAScript 6 also has some new features that reduce the ceremonial aspect of coding. Concise method definition provides a compact way to define a function within an object, making it symmetrical to the way its properties are defined. As evidenced from the following example, there is no need to use the keyword function anymore.

	// ES 6
	var Person = {
	  name: 'Joe',
	  hello() { console.log('Hello, my name is', this.name); }
	};

A function that serves as a callback (not part of an object) can enjoy a shortcut notation as well via the use of the arrow function. For example, the following code computes the squares of some numbers:

	// ES 5
	[1,2,3].map(function (x) {
	  return x * x;
	});

The ECMAScript 6 version can be shorter:

	// ES 6
	[1,2,3].map(x =&gt; x * x);

With the use of the arrow function (=>), we no longer need the function and return keywords. The last expression within the function body becomes the return value. Note that, if the function needs to accept two parameters or more, those parameters must be enclosed with parentheses.

The new spread operator in ECMAScript 6 can be used to reduce the run-time boilerplate code. It is quite common for a seasoned developer to use apply creatively, in particular when an array needs to be used as the list of function arguments. An example of such usage is:

	// ES 5
	var max = Math.max.apply(null, [14, 3, 77]);

Fortunately, this kind of confusing construct will not be the norm anymore. The spread operator “…,” as the name implies, spreads the forthcoming array into the proper arguments for the said function.

	// ES 6
	var max = Math.max(...[14, 3, 77]);

Another use of the spread operator is for rest parameters. This is the exactly the opposite of the example above: now we must convert variable function arguments into an array. To appreciate the importance of this, take a look at the following code:

	// ES 5
	store('Joe', 'money');
	store('Jane', 'letters', 'certificates');
	function store(name) {
	  var items = [].slice.call(arguments, 1);
	  items.forEach(function (item) {
	    vault.customer[name].push(item);
	  });
	}

Here we have a vault in the bank and we want to store an unlimited amount of belongings to the corresponding customer’s safe deposit. With such an API, the function store needs to cast a magical spell with the special object arguments so that it can convert the passed belongings into an array and then push the array elements to the right location. This is far from being clear, it is certainly a code smell.

That run-time hassle is finally gone in ECMAScript 6 with the use of the spread operator for the rest parameters, as demonstrated in the following snippet, re-written for ECMAScript 6:

	// ES 6
	store('Joe', 'money');
	store('Jane', 'letters', 'certificates');
	function store(name, ...items) {
	  items.forEach(function (item) {
	    vault.customer[name].push(items)
	  });
	}

For those who love functional programming, the new array comprehension syntax will be strikingly familiar. Basically, this permits a more natural construct compared to the use of Array’s higher-order functions. For example, the following simple iteration with Array.prototype.map:

	// ES 5
	[1, 2, 3].map(function (i) { return i * i });

will have a different look when rewritten using array comprehension:

	 // ES 6
	[for (i of [1, 2, 3]) i * i];

Obviously, array comprehension supports filtering, much like the use of Array.prototype.filter. Compare the following two variants:

	// ES 5
	[1,4,2,3,-8].filter(function(i) { return i &lt; 3 });
 
	// ES 6
	[for (i of [1,4,2,3,-8]) if (i &lt; 3) i];

Even better, array comprehension can handle multiple iterations, much like nested loops in the imperative style. For example, the following one-liner produces all possible chess positions (a1 to h8):

	// ES 6
	[for (x of 'abcdefgh'.split('')) for (y of '12345678'.split('')) (x+y)];

Run-Time Renaissance

In addition to the above-mentioned incremental improvements to the language syntax, ECMAScript 6 also offers some run-time changes that improve the life of web developers. Two things which relate directly to the development of large-scale applications are class and modules.

The new class syntax is designed to be concise and easy to understand. The following example code shows how to create a simple class:

	// ES 6
	class Vehicle {
	  constructor(color) {
	    this.color = color;
	    this.speed = 0;
	  }
	  drive() {
	    this.speed = 40;
	  }
	}

A class method with the name constructor has a special meaning, it acts as (surprisingly) the class constructor. Other than that, everything resembles the familiar concept of class as in many other programming languages.

Written in today’s ECMAScript 5, this Vehicle class would look like:

	// ES 5
	function Vehicle(color) {
	  this.color = color;
	  this.speed = 0;
	}
 
	Vehicle.prototype.drive = function() {
	  this.speed = 40;
	}

Use the keyword extends to derive a new class from the base class, as illustrated below. Note the use of super within the constructor, which provides a way to call the constructor of the parent class.

	// ES 6
	class Car extends Vehicle {
	  constructor(brand, color) {
	    super(color);
	    this.brand = brand;
	    this.wheels = 4;
	  }
	}

Again, this subclassing is just a syntactic sugar. Doing it by hand would have resulted in the following equivalent code:

	// ES 5
	function Car(brand, color) {
	  Vehicle.call(this, color);
	  this.brand = brand;
	  this.wheels = 4;
	}
 
	Car.prototype = Object.create(Vehicle.prototype);
	Car.prototype.constructor = Car;

The built-in support for handling modules is extremely important. Modern web applications grow in complexity and to date, structuring various parts of the application to be modular required a lot of effort. There are libraries, loaders, and other tools to ease the burden but developers have had to sink time in learning these non-standard solutions.

Module syntax is still being discussed and finalized. To get a taste of what is possible, take a look at the following fragment which forms a simple module.

	const HALF = 0.5;
	export function sqrt(x) {
	  return Math.exp(HALF * Math.log(x));
	}

Assuming this code lives in a file (or module) called mathlib.js, we can later use the function sqrt from another place. This is possible because that function is exported, as indicated by the keyword export. While the above example shows an exported function, there are many other values that can be exported: variables, objects, and classes. Also, note that the constant HALF is not exported and hence it is only visible within this module.

How do we use the module? From another source file, we can simply import the function using the keyword import following this syntax:

	import { sqrt } from ‘mathlib’;
	console.log(sqrt(16));

While the above use case suffices for the common cases, ECMAScript 6 module support goes well beyond this. For example, it is possible to define inline modules, rename exported values, declare default export and import. In addition, there will be a loader system to facilitate dynamic module resolution and loading.

Another interesting run-time feature of ECMAScript 6 is the generator function, which is very useful for suspending and resuming program execution within a function. The use of generators, particularly for sequential operations, is an alternative to the asynchronous approach using callback which has led many developers into “callback hell”.

Within the generator function, yield suspends the execution and next resumes it. The following fragment illustrates a very simple generator:

	function* foo() {
	  yield 'foo';
	  yield 'bar';
	  yield 'baz';
	}
 
	var x = foo();
	console.log(x.next().value); // 'foo'
	console.log(x.next().value); // 'bar'
	console.log(x.next().value); // 'baz'

Back from the Future

Browsers like Firefox and Chrome (with an experimental flag) are starting to support some of the above mentioned ECMAScript 6 features, but ECMAScript 6 is still far from universally available in its entirety. Fortunately, there is a possible solution to that, namely using a transpiler which converts code written in ECMAScript 6 into something that today’s browsers can execute.

A popular choice for an ECMAScript 6 transpiler is Traceur, a project from Google (GitHub: github.com/google/traceur-compiler). Traceur supports many features of ECMAScript 6, it generates translated code which runs quite well on modern browsers.

Another alternative is to start adopting TypeScript from Microsoft (http://www.typescriptlang.org/). TypeScript is not necessarily equivalent to ECMAScript; it can be viewed as a subset of ECMAScript. TypeScript supports popular features which are part of ECMAScript 6 but at the same time it also adds optional static typing.

Traceur and TypeScript are open-source projects that can be used in many environments. Beside these two projects, there are also other transpiler with a more specific purpose such as es6-module-loader (dynamic module loading), defs.js (only for let and const), and many others.

Final Words

With the modernization to the syntax, richer built-in objects, as well as being compilation-friendly, ECMAScript 6 paves the way to a brighter future for building large-scale web applications. We are excited to see where ECMAScript 6 is heading and we are evaluating the ways we may be able to use the changes in our frameworks!

P.S: Special thanks to Axel Rauschmayer for his technical review of this article.

20130807-es6.png No Comments   Read more

5 Myths About Mobile Web Performance

Recently we’ve heard some myths being repeated about mobile HTML performance that are not all that accurate. Like good urban myths, they sound compelling and plausible. But these myths are based on incorrect premises, misconceptions about the relationship between native and web software stacks and a scattershot of skewed data points. We thought it was important to address these myths with data that we’ve collected over the years about performance, and our own experiences doing optimizations of mobile web app performance.

### TL;DR

#### Myth #1: Mobile web performance is mostly driven by JavaScript performance on the CPU
Reality: Most web performance is constrained by the optimization of rendering pipelines, speed of DOM interactions and degree of GPU acceleration. Faster JavaScript is always helpful, but it’s rarely critical.

#### Myth #2: CPU-Bound JavaScript has only become faster because of hardware improvements (aka Moore’s Law)
Reality: 50% of mobile JavaScript performance gains over the last four years has come from software improvements, not hardware improvements. Even single-threaded JavaScript performance is still improving, without considering that most app devs are using Web Workers to take advantage of multi-threading where possible.

#### Myth #3: Mobile browsers are already fully optimized, and have not improved much recently
Reality: Every mobile browser has a feature area where it outperforms other browsers by a factor of 10–40x. The Surface outperforms the iPhone on SVG by 30x. The iPhone outperforms the Surface on DOM interaction by 10x. There is **significant** room to further improve purely from matching current best competitive performance.

#### Myth #4: Future hardware improvements are unlikely to translate into performance gains for web apps
Reality: Every hardware generation in the last three years has delivered significant JavaScript performance gains. Single thread performance on mobile will continue to improve, and browser makers will advance the software platform to take advantage of improved GPU speeds, faster memory buses & multi-core through offloading and multi-threading. Many browsers already take advantage of parallellism to offload the main UI thread, for example: Firefox offloads compositing; Chrome offloads some HTML parsing; and IE offloads JavaScript JIT compiliation.

#### Myth #5: JavaScript garbage collection is a performance killer for mobile apps
Reality: This is trueish but a little outdated. Chrome has had an incremental garbage collector since Chrome 17 in 2011. Firefox has had it since last year. This reduced GC pauses from 200ms down to 10ms — or a frame drop vs, a noticeable pause. Avoiding garbage collection events can deliver significant improvements to performance, but it’s usually only a killer if you’re using desktop web dev patterns in the first place or on old browsers. One of the core techniques in Fastbook, our mobile HTML5 Facebook clone, is to re-cycle a pool of DOM nodes to avoid the overhead of creating new ones (and the associated overhead of GC collections on old ones). It’s very possible to write a bad garbage collector (cf. old Internet Explorers) but there’s nothing intrinsically limiting about a garbage collected language like JavaScript (or Java).

### Ok: The Essentials
First, let’s remind ourselves of the basics. From 50,000 feet, the browser is a rich and complex abstraction layer that runs on top of an Operating System. A combination of markup, JavaScript, and style-sheets, uses that abstraction layer to create application experiences. This abstraction layer charges a performance tax, and the tax varies depending on what parts of the abstraction layer that you’re using. Some parts of the abstraction layer are faster because they match the underlying OS calls or system libraries closely (aka Canvas2D on MacOS). Some parts of the abstraction layer are slower because they don’t have any close analog in the underlying OS, and they’re inherently complicated (DOM tree manipulation, prototype chain walking).

At Sencha, we know that a good developer can create app experiences that are more than fast enough to meet user expectations using mobile web technologies and a modern framework like Sencha Touch.”

Very few mobile apps are compute intensive: no-one is trying to do DNA sequencing on an iPhone. Most apps have a very reasonable response model. The user does something, then the app responds visually with immediacy at 30 frames per second or more, and completes a task in a few hundred milliseconds. As long as an app meets this user goal, it doesn’t matter how big an abstraction layer it has to go through to get to silicon. This is one of the red herrings we’d like to cook and eat.

At Sencha, we know that a good developer can create app experiences that are more than fast enough to meet user expectations using mobile web technologies and a modern framework like Sencha Touch. And we’ve been encouraged by the performance trends on mobile over the last 3 years. We’d like to share that data with you in the rest of the post.

It’s not our intention to claim that mobile web apps are **always** as fast as native, or that they are always comparable in performance to desktop web apps. That wouldn’t be true. Mobile hardware is between 5x and 10x slower than desktop hardware: the CPU’s are less powerful, the cache hierarchy is flatter and the network connection is higher latency. And any layer of software abstraction (like the browser) can charge a tax. This is not just a problem for web developers. Native iOS developers can tell you that iOS CoreGraphics was too slow on the first Retina iPad, forcing many of them to write directly to OpenGL.

### Digging Deeper Into the Myths
Having worked for three years on optimization in Sencha Touch for data driven applications, we can say with confidence that we’ve rarely been stymied by raw JavaScript performance. The only significant case so far has been the Sencha Touch layout system, which we switched over to Flexbox after finding JavaScript to be too slow on Android 2.x.

Far more often, we’ve run into problems with DOM interactions, the browser rendering engine and event spam. All of these are limitations created by the architects and developers of each browser, and nothing to do with the inherent characteristics of JavaScript or JavaScript engines. As one example, when we’ve worked with browser makers on performance optimization, we’ve seen a 40x improvement in one of the browser operations (color property changes) that bottleneck our scrolling list implementation, as just one example.

### JavaScript Performance on iOS & Android
Although we’ve said JavaScript performance isn’t that important on mobile, we want to demolish the myth that it’s not improving. Below is a graph showing a four year history of SunSpider scores on iOS (lower is better) by model and by iOS version. (Luckily, SunSpider is a very widely used test, so there are records all over the web of testing performed on older iOS versions.) In 2009, the original iPhone 3GS running iOS3 had a score of over 15,000 — quite a poor performance, and about a 30x performance gap vs. the 300–600ish score of desktop browsers in 2009.

5 Myths about Mobile Web Performance

However, if you upgraded that iPhone 3GS to iOS4, 5 and 6, you’d have experienced a 4x improvement in JavaScript performance on the same exact hardware. (The big jump in performance between iOS 4 and iOS5 is the Nitro engine.) The continual gains in SunSpider continue in iOS7, but we’re still under NDA about those. Compared with today’s desktop browsers, edge mobile browsers are now about 5x slower — a big relative gain vs. 2009’s 30x gap.

For even more detail on hardware and software advances in iOS hardware, see Anandtech’s review from last October.

There have been similar levels of improvement in the Android platform. From our testing lab, we assembled a collection of Android platforms from the last three years that we believe represent typical high end performance from their time. The four phones we tested were:

* Samsung Captivate Android 2.2 (Released July 2010)
* Droid Bionic Android 2.3.4 (Released September 2011)
* Samsung Galaxy Note 2 Android 4.1.2 (Released September 2012)
* Samsung Galaxy S4 Android 4.2.2 (Released April 2013)

As you can see below, there has also been a dramatic improvement in SunSpider scores over the last four years. The performance jump from Android 2.x to Android 4.x is a 3x improvement.

5 Myths about Mobile Web Performance

In both cases, the improvement is better than what we’d expect from Moore’s Law alone. Over 3 years, we’d expect a 4x improvement (2x every 18 months), so software is definitely contributing to the improvement in performance.

### Testing What Matters
As we previously mentioned, SunSpider has become a less interesting benchmark because it only has a faint connection with the performance of most applications. In contrast, DOM Interaction benchmarks as well as Canvas and SVG benchmarks can tell us a lot more about user experience. (Ideally, we would also look at measurements of CSS property changes as well as the frames per second of css animations, transitions and transforms — because these are frequently used in web apps — but there are still no hooks to measure all of these correctly on mobile.)

First DOM interaction tests: we used Dromaeo Core DOM tests as our benchmark. Below are the results from testing on our 4 Android models. We indexed all Core DOM results (Attributes, Modifications, Query, Traversal) to the Captivate’s performance, and then took the average of the 4 Core DOM indices.

5 Myths about Mobile Web Performance

As can be seen, there was a 3.5x performance improvement from Android 2.x to 4.x, although the S4 was only a minor improvement on the Note 2. We can also look at Dromaeo results on iOS. Sadly, we can’t do a comparison of performance across older versions of iOS, but we can show the steady improvement across multiple generations of iPhone hardware. Interestingly, the performance improvement even within iOS6 across these device generations is better than the increase in CPU speed, which means that improvements in memory bandwidth or caching must be responsible for the better than Moore’s Law performance increase.

5 Myths about Mobile Web Performance

In order to show that there is still a lot of potential for browsers to match each other’s performance, we also benchmarked the Surface RT. The poor performance of DOM interactions in IE has always been a source of performance frustration, but it’s worth pointing once again the large performance gap in DOM interaction performance on the iPhone vs. the Microsoft Surface RT running IE10. One of the myths we’d like to destroy is that the mobile software stack is as good as it gets. This is not true for Windows RT- a 10x performance gap is waiting to be filled. (We’ll show where iOS falls down in a later benchmark.)

### Graphics Benchmarks
In addition to significant improvements in JavaScript and DOM interaction, we also wanted to show improvements in Canvas and SVG Performance. In iOS5, we previously found that Canvas2D performance increased by 5–8x on the same hardware vs. iOS4. [Some micro-benchmarks ran 80x faster on the iPad 2 when upgraded to iOS5](/blog/apple-ios-5-html5-developer-scorecard/). And because Canvas is closely bound to CoreGraphics on the iPhone, when native graphics gets faster, so does Canvas. In this round of testing, we used the mindcat Canvas2D benchmark to measure performance. Here, we see a substantial increase in Canvas performance on multiple generations of iPhone hardware — all running the same generation of iOS.

5 Myths about Mobile Web Performance

And remember, this is on top of a big performance gain from iOS4 to iOS5. As can be seen, the performance improvement in Canvas2D performance (7x) is better than the CPU improvement over the same time period (4x) and reflects the improved GPU and GPU software stack on the iPhone over time. GPU improvements and the increased use of GPU acceleration needs to be factored in to the increase in mobile web performance improvement.

5 Myths about Mobile Web Performance

When we look at the same tests on Android, we see an interesting data point — a lack of correlation between CPU performance and Canvas. The big change from Android 2 is that Android 2 had no GPU acceleration of Canvas at all. Again, a purely software change — GPU acceleration — is the big driver of performance improvement.

### SVG Benchmarks
SVG is another area that shows the broader story about web performance. Although not as popular as Canvas (largely because Canvas has become so fast), SVG has also shown solid performance improvements as hardware has improved. Below is a test from Stephen Bannasch that tests the time taken to draw a 10,000 segment SVG path. Once again, the test shows constant steady improvement across hardware generations as the CPU and GPUs improve (since these are all on iOS6).

5 Myths about Mobile Web Performance

The main gap in performance is in software: the Surface RT is more than **30x faster** than the iPhone 5 (or the iPad 4 — we also tested it but haven’t shown it.) In fact, the Surface RT is even 10x faster than Desktop Safari 6 running on my 1 year old Macbook! This is the difference that GPU acceleration makes. Windows 8/IE10 fully offloads SVG to the GPU, and the result is a huge impact. As browser makers continue to offload more graphics operations to the GPU, we can expect similar step-function changes in performance for iOS and Android.

In addition to long path draws, we also ran another SVG test from Cameron Adams that measures the frames per second of 500 bouncing balls. Again, we see constant performance improvement over the last four generations of hardware.

5 Myths about Mobile Web Performance

What’s more interesting than the improvement is the absolute fps. Once animations exceed 30 frames per second, you’ve exceeded the fps of analog cinema (24 fps) and met viewer expectations for performance. At 60 fps, you’re at the buttery smoothness of GPU accelerated quality.

### Real World Performance: Garbage Collection, Dynamic Languages and More
We hope that the preceding tour through mobile performance has demonstrated a few things, and demolished a few myths. We hope we’ve shown that:

* JavaScript performance continues to increase rapidly
* This performance increase is driven by both hardware and software improvements
* Although this is a “good thing”, much of app performance has nothing to do with JavaScript CPU performance
* Luckily, these other parts that impact performance are also improving rapidly, including DOM interaction speed, Canvas and SVG.

And although we could show it with high speed camera tests, all mobile web developers know that performance of animations, transitions and property changes has vastly improved since the days of Android 2.1, and they continue to get better each release.

So having slain a few false dragons, let’s mix metaphors and tilt at some real windmills. The last claim we’ve heard going around is that mobile web apps will **always be slow** because JavaScript is a dynamic language where garbage collection kills performance. There is definitely some truth in this. One of the benefits of using a framework like Sencha Touch, where DOM content is generated dynamically, is that we manage object creation and destruction as well as events at a level above the browser in the context of a specific UI component. This enables, for example, 60fps performance for data-backed infinite content (grids, lists, carousels) by recycling DOM content, throttling events and prioritizing actions.

Without this level of indirection, it’s very easy to produce poor performing mobile web app experiences — like the first generation mobile web app from Facebook. We believe that applications written on top of UI Frameworks like jQuery Mobile that are too closely tied to the underlying DOM will continue to suffer from performance problems for the foreseeable future.

### Bringing It All Together
There is a lot of data and a lot of different topics covered in this piece, so let me try to bring it all together in one place. If you’re a developer, you should take a few things away from this:

* Mobile platforms are 5x slower than desktop — with slower CPUs, more constrained memory and lower powered GPUs. That won’t change.
* Mobile JavaScript + mobile DOM access is getting progressively faster, but you should still treat the iPhone 5 as if it’s a Chrome 1.0 browser on a 2008-era desktop (aka 5–10x faster than desktop IE8).
* Graphics have also been getting much faster thanks to GPU acceleration and general software optimization. 30fps+ is already here for most use cases.
* Garbage collection and platform rendering constraints can still bite you, and it’s essential to use an abstracted framework like Sencha Touch to get optimal performance.
* Take advantage of the remote debugging and performance monitoring capabilities that the mobile web platforms: Chrome for Android now has a handly fps counter, and compositing borders can show you when content has been texturized and handed off to the GPU and how many times that texture is then loaded.

We hope that the review of performance data has been a helpful antidote to some of the myths out there. I want to thank everyone at Sencha who contributed to this piece including Ariya Hidayat for review and sourcing lots of links to browser performance optimizations, and Jacky Nguyen for detail on Sencha Touch abstractions and performance optimizations.

20130730-5-html5-myths.png No Comments   Read more

Learn about the Salesforce Mobile Platform Services at SenchaCon

Guest Blog Post

salesforce platform mobile services

The Salesforce Platform Mobile Services are a set of tools, frameworks, and APIs to help you rapidly build enterprise mobile apps for any device. The Salesforce Platform Mobile Services pair with your mobile app just as seamlessly as Force.com pairs with your enterprise apps. It is a powerful MBaaS providing mobile developers backend storage and additional features like configurable security, secure offline storage, and push notifications amongst several other platform services. We’re pleased to announce that in an upcoming launch we’ll be releasing new mobile packs centered around Sencha Touch.

Sencha is the peanut better to our jelly and the mobile packs are a working example of their UI-made-easy paired with our MBaaS-made-easy. In just a few weeks, Josh Birk and I will be presenting some sessions at SenchaCon—Josh will be talking about Integrating Sencha Apps with the Salesforce Platform and I’ll be talking about Salesforce Platform Mobile Services with Sencha Touch.

Come say ‘Hi!’ at SenchaCon

Salesforce will have a big presence at SenchaCon this year, so if you’re around come say hello either in person or via tweet. As mentioned above, we’ll have two developer sessions in the breakout tracks, and we’ll also have a Salesforce Platform lounge in the expo area. The lounge will consist of demo stations, ‘Ask an Expert’, and a quick hands-on mobile area. We’ll also be hosting several giveaways throughout the event, from FREE t-shirts, hoodies, mochi and a chance to win a Macbook Air.

Looking forward to the event and all of the new things in store for the expanding Salesforce Mobile Platform Services! Even if you can’t make the event, definitely check out our mobile packs to jumpstart web mobile development with one of your favorite open-source JavaScript frameworks.

20130705-salesforce-mobile-platform.png No Comments   Read more