July 21st, 2011 by radu

I have written a small helper function to make delayed sequential function execution easier.

We have the following case: we need to execute an array of functions. The second one has to execute after the first one finishes, the third after the second and so one. The scenario gets a bit more complicated when wee need some delay between functions. So we have to execute function 1, then after it finishes, wait for 200 ms, and execute function 2, then after another 500 ms execute function 3 and so on.

So the code is the following:

function runSequence(arr, scope, delay){
	arr.push(function(){});
	delay = delay || 0;

	var i = 0,
             len = arr.length;

	for(;i < len-1; i++){
		(function(index, thisObject){
			arr[index] = function(){
				var isFn = !!thisObject.call,
					fn = isFn? thisObject : thisObject.fn,
					fnScope = isFn? scope: thisObject.scope,
					fnDelay = isFn? delay : thisObject.delay,
					fnToExecute = function(){ fn.call(this); arr[index+1](); }

                                fnScope = fnScope || this;
				fnDelay? setTimeout(function(){ fnToExecute.call(fnScope) }, fnDelay) : fnToExecute.call(fnScope);
			}
		})(i, arr[i]);
	}

	arr[0]();
}

We can do the following:

runSequence([
	{ fn: function(){ console.log('executed immediately') }, delay: 0 },
	{
          fn: function(){ console.log('this was after 1500 ms, with scope: ', this.name) },
          delay: 1500,
          scope: {name: 'sequence running'}
        },
	{ fn: function(){ console.log('this was after 2s ') }, delay: 2000 }
], this)
/*
 * The first and the last functions above are executed in the scope of the code executing the runSequence function
 * The second function is instead called with the scope being the passed object, {name: 'sequence running'}
 */

or the following:

runSequence([
	function(){ console.log('first after 200ms') },
	function(){ console.log('yet another 200 ms') },
	function(){ console.log('the last fn at 200ms') }
], this, 200)
/*
 * A shorter form of the runSequence function call, with functions running at equal timeouts, in the passed 'this' scope
 */

This function can be useful when processing large amounts of data that would otherwise block the browser, or in cases when one would need to trigger ajax calls with a certain delay in between. I’m sure that there are other cases when this could prove useful.
In the case of processing large amounts of data, one could use this to fill up a (non-paginated) grid with data, in chunks of, say, 200 records.

Do you find this pattern useful?

March 25th, 2011 by radu

Lately I had to do more work with ExtJS x-templates, and really found them very flexible. One feature I find useful is the support for formatting functions. So you can have a template which outputs different things for plural and singular forms:

new Ext.XTemplate('{0:plural("record","records")} deleted').apply([4])
// -> 4 records deleted

This is nice. Yet the formatting functions are not limited to just a few. Templates support all formatting functions in Ext.util.Format. What’s even better is that you can add your own formatting functions and have them in the templates.

One use case for this usage of templates is displaying user feedback in a label or tooltip when deleting records in a grid, or selecting records. In order to be accurate and give a nice user experience, it would be nice to output: ‘No records selected’, and not ‘0 records selected’; ‘One record selected’, and not ‘1 record selected’. So, a nice solution would be the following:

(function() {

    Ext.apply(Ext.util.Format,{

        /**
         * Label plural formatter : lplural - to be used with templates
         *
         * @param value {Number} number
         * @param singular {String} singular form
         * @param plural {String} plural form
         * @param zero {String} zero form
         * @param addPluralValue {Boolean} whether to add
         *            the value in the plural form
         */
        lplural: function(value, singular, plural, zero, addPluralValue){
            //make the text for the zero quantity be optional
            if (zero && !value){
                return zero;
            }

            //also the addPluralValue flag is optional - if it is true,
           //also return the value: eg - 5 records
            plural = addPluralValue? (value + ' ' + plural) : plural;

            return value != 1 ? plural : singular;
        }
    })

    Ext.onReady(function(){

        var t = new Ext.XTemplate('{0:lplural("one record","records","no records", true)}');

        //add plural value
        console.log(t.apply([5])) // -> 5 records

        console.log(t.apply([0])) // -> no records
        console.log(t.apply([1])) // -> one record

        var t = new Ext.XTemplate('{0:lplural("one record","records", null , false)}');

        //don't output the '5'
        console.log(t.apply([5])) // -> records
       //haven't provided a text for zero, so defaults to the plural form
        console.log(t.apply([0])) // -> records
    })
})();

I really think templates are very powerful, so use them! Any other clever usages? (besides all the ext4 being built on top of them :) )

November 26th, 2010 by radu

Recently I got borred with the for loops and I added the “times” function on the prototype of Number. As a result, I can easily iterate over arrays or I can simply call a function how many times I want like this:

     (5).times(function(index /* zero based */){
           console.log(index);
     })
     //or using array length
     arr.length.times(function(){ ... });

     //optionally specify scope for the callback function:
    n.times(function(){ .... }, scope);

Together with this, I’m using another goodie. Whenever I have a function that expects a parameter which can either be a simple value or an array, convert that value to array in one line, like:

    var arr = [].concat(valueOrArray);

See below the source code.

/**
 * extend the Number prototype
 * @param func
 * @param scope [optional]
 */
Number.prototype.times = function(func, scope){
    var v = this.valueOf();
    for (var i=0; i < v; i++){
        func.call(scope||window,i);
    }
};

function test(valueOrArray){
    var arr = [].concat(valueOrArray)
    arr.length.times(function(i){
        console.log(arr[i]);
    })
}

test([1,3,4])
//output: 1   3   4

test(123)
//output: 123

As for the performance, I have tested the times function against the for loop, and it seems to give about same results at a first glance. Any feedback on this?

P.S. Iterating over arrays gets even easier by adding an 'each' function to the Array prototype. Adding to the prototype of standard JavaScript objects is a debatable practice, and should not be abused.

September 12th, 2010 by radu

Well, as many of you know, the guys from Sencha are already working on ExtJS 4, and will be showing an preview at the Sencha Conference in San Francisco. As I won’t attend (there’s quite a distance from Cluj-Napoca, Romania to San Francisco), I am expressing here some opinions on what I think would be nice to have in the upcoming ExtJS version. All these are gathered in one full year of experience and heavy development with ExtJS, and previous years of experience with JavaScript and some jQuery.

  1. Keep the DOM small. I know all the DOM elements in ExtJS have a reason and they are needed in order to have nicely rounded corners in all browsers and consistent behavior. Yet it’s quite too much, especially for large applications. I am currently developing a large web 2.0 application with ExtJS and on older browsers the performance is a big issue (you should read IE 7 and 8). The application behaves well with Firefox 3.5+ and runs the smoothest with Chrome. But when having more than just 2,3 windows and a simple grid, when you have live events and Comet notifications, stores sharing data and large UI controls, you have to start thinking on how to keep everything running smoothly. The next points touch on keeping the DOM small as well.
  2. Drop IE 6 support. We all hate it. Google dropped it and so should the team at Sencha. All the DOM elements are needed for old browsers like IE 6. But we could drop support for it and have a smaller DOM, so better performance and happier users. Those who still need IE 6 can continue on the 3.x ExtJS branch. Come on, we now have HTML5 and CSS3. I know the adoption is not the best, but hey, we are web developers, let’s push at least for a minimum subset of it to be out there.
  3. Integrate Raphael graphs. It was nice to see Sencha being formed and acquiring Raphael and jqTouch. We now saw jqTouch contributing to Sencha Touch. The next normal step I think is to integrate Raphael graphs into ExtJS. I really suppose this is the intention, but let’s mention it upfront, just in case. It’s nice to have charting, but Flash is not the best sollution.
  4. Give us an integrated test platform. Testing is important, but we don’t see it so often in our own ExtJS apps. Yes, we test with Selenium, and this is a great tool, but show us the testing framework in ExtJS. As far as I know, the Sencha team is using a customized YUI Test framework. Would be nice if they shared it, so we can all benefit.
  5. Custom theming. This is a well known issue, but let’s just recap we need this. ExtJS would benefit from a much larger adoption if they had an easy way to build themes, like the jQueryUI theme roller. Let’s face it, on this issue, jQuery is far more attractive. I didn’t like to say it, but that’s the truth. With the help of a designer I have put up a custom theme, and yes…. you have a bit of headache. It’s not like you’re building it in one day, if you want something a bit more complicated and flashy. It was nice to see SASS being used in Sencha Touch. This is a first step towards easy, custom theming.
  6. Distribution builder. ExtJS is very nice, but sometimes you just need a bit of it. You just want a window and a grid, so importing the whole library is quite expensive. I know this was present with the ExtJS 2 distribution, and let’s hope we’ll have it back again. A workaround on this would be using the Google Closure JavaScript Compiler to have the unused code removed from our apps. Then we would still have problems with the ‘xtype‘ config, and would probably need to artificially instantiate all the components which have their xtype used in the application. Anyway, this is just an idea to try out, but it would be nice to have something from the official distribution.

These are not all the issues that would be nice to have, but at least the most important that come to mind. It’s nice to see the ExtJS ecosystem at work and new components popping up, like the pivot grid, the calendar etc.

So… looking forward to ExtJS version 4 and hoping to see that many (why not all?) of these issues find their way into the framework. Looking forward to see the great work! Keep up!

July 14th, 2010 by radu

Automation testing of UI is essential in any big project, but it is difficult to achieve this for user interfaces built with ExtJS. Selenium records user actions, by clicks on elements, and memorizes the ids of the selected elements. Yet since ExtJS auto-generates ids which are not guaranteed to stay the same, you cannot rely on this. The same problem is when you simply add a small change (add a label, etc), so the generation (if you relied on it to be the same) will totally change and the automated tests will be ruined.

Instead, Selenium tests for ExtJS should rely on CSS selectors. For every button, grid, label, tab or any significant UI element, I simply chose to use the cls attribute and specify a CSS class.

new Ext.Button({
    text: 'Ok',
    cls: 'seleniumOkButton', //can have more classes, separated by space
    scope: this,
    handler: function(){ ... }
})

This is how a basic button that is used in automation testing looks like. And I use the following XPath selector in Selenium:

//table[contains(@class,'seleniumOkButton')]

Happy automated testing!

May 31st, 2010 by radu

Well, if you are programming in JavaScript for a while, you are familiar with the arguments ‘array’ which gives you access to function arguments by index, without the need of argument names. And if you are programming JavaScript for a bit longer while, you will know that arguments is not even a normal array. It does not have any methods of an array. You can just use it to access items by index and also access it’s length property. That’s all. What if you want to make a copy of the array? What if you want to push or pop items? Well… you have some work to do… OR …

Or do something smart. Like call the slice method from Array.prototype on the arguments, something like:

//this makes a copy of the arguments and returns a true array
Array.prototype.slice.call(arguments, 0) 

//pushes the value '5' in the arguments
Array.prototype.push(arguments, 5)
//this is not valid: arguments.push(5)

Well, maybe most of you expert JavaScript programmers have thought about this, and this is not a news. But, let’s share from our experience to the more novice/newcomers to JavaScript and show them the beauty of this language!

JavaScript is a great language! It’s expressive! It’s powerful! That’s why we love JavaScript.

May 26th, 2010 by radu

I like ExtJs and the way it is so modular. This time I needed to have something very easy, which is not implemented by default in Ext, so I rolled my own. I needed windows to fire ‘tofront’ and ‘toback’ events. In an app I am working on, the user can have quite many windows opened and I needed to know programatically when a window comes to front (and to back). The approach was to override the toFront method in Ext.Window. Below you can see the code, with some basic comments.

NOTE: I know there are the activate and deactivate events on every window, but when a window triggers the ‘deactivate’ event, Ext.WindowMgr.getActive() still returns it as the active window. This is why I needed the ‘tofront’ and ‘toback’ events.

(function(){

    // get the previous implementation of the toFront method
    var prevToFront = Ext.Window.prototype.toFront;

    Ext.override(Ext.Window, {

        toFront: function(){

            //get the window manager of this window, or Ext.WindowMgr if it doesn't have one
            var manager = (this.manager || Ext.WindowMgr);
            //get the window which is currently to front
            var activeWindow = manager.getActive();

            prevToFront.apply(this, arguments);

            //only fire tofront and toback events if the current window was not already to front
            if (this != activeWindow){
                this.fireEvent('tofront');
            }

            if (activeWindow){
                activeWindow.fireEvent('toback');
            }

            return this;
        }

    });
})();

I needed to run code both before and after the default implementation of the toFront method. If I didn’t need this, an easier approach would have been to use createSequence:

Ext.override(Ext.Window,{
       toFront: Ext.Window.prototype.toFront.createSequence(function(){
             // code here.
       })
})

Nice ExtJs! Go try it!

April 1st, 2010 by radu

Recently I needed a text field in ExtJS that doesn’t allow user input to start with space. So I thought it would be useful for others as well. I chose to override the original Ext.form.TextField and make all the textfields in the application have this behaviour.

Here is the code for this:

(function(){
    //put all the code in an anonymous function to hide the local variables from the global namespace

    //methods that will be overriden - keep the original
    var originalFilterKeys = Ext.form.TextField.prototype.filterKeys;
    var originalInitEvents = Ext.form.TextField.prototype.initEvents;

    Ext.override(Ext.form.TextField,{

        // private
        filterKeys : function(e){
            var res = originalFilterKeys.apply(this, arguments);

            var cc = String.fromCharCode(e.getCharCode());

            //if the caret is in the first position, and the typed character
            //was space, stop the event
            if (cc == ' ' && (this.getCaretPos(this.el.dom) == 0) ){
                e.stopEvent()
            }

            //the case when the text is selected and the user presses space
            if (cc == ' ' && this.getSelectedText() == this.getValue()){
                //clear value of the text field
                e.stopEvent();
                this.setValue('');
            }

            return res; //return original result
        },

        /**
         * @return String the selected text or '' if none
         */
        getSelectedText: function(){
            var dom = this.el.dom;
            var selected = (dom.value).substring(this.getSelectionStart(), this.getSelectionEnd());

            return selected;
        },

        getSelectionStart: function(){
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionStart;
            } else if (document.selection) { // IE
                var pos, textRange = document.selection.createRange().duplicate();

                if (textRange.text.length > 0) { // selection is not collapsed
                    pos = input.value.indexOf(textRange.text);
                } else { // selection is collapsed
                    pos = 0;
                }

                return pos;
            }
            return 0;
        },

        getSelectionEnd: function() {
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionEnd;
            } else if (document.selection) { // IE
                var selectedRange = document.selection.createRange().duplicate();
                if (selectedRange.text.length > 0){
                    selectedRange.moveStart("character", -input.value.length);
                }
                return selectedRange.text.length;
            }

            return 0;
        },

        /**
         * @return int - the current index of the caret
         */
        getCaretPos: function() {
            var input = this.el.dom;
            var pos = 0;
            if (input.createTextRange) {
                var range = document.selection.createRange().duplicate();
                range.moveStart('textedit',-1);
                pos = range.text.length;
            } else if (input.setSelectionRange) {
                pos = input.selectionEnd;
            }
            return pos;
        },

        // private
        initEvents : function(){
            this.maskRe = new RegExp('.*'); //I just needed a reg exp to match all characters
            //as filterKeys method is only called if the textfield has a 'maskRe' property
            return originalInitEvents.call(this);
        }
    })

})()

Hope it helps! Enjoy the code. If you have any questions, let me know!

March 21st, 2010 by radu

As I have promised in this post, I am giving a review of the ADVANCED_OPTIMIZATIONS option in Google Closure JavaScript Compiler.

Beyond simply shortening variable names, Closure Compiler with ADVANCED_OPTIMIZATIONS, does three other important steps:

  • aggresive renaming – not only renaming local variables and functions, but it renames GLOBAL variables and functions. In this way, it can ruin your public API
  • dead code removal – it removes functions you are not using and segments of unreachable code. This can be fine for some apps, but it is definitely risky for JavaScript libraries, that expose some functions which are supposed to be called only by client code.
  • function inlining – inserting the function’s body instead of the function call, where appropriate

So it is true that without some additional work, the ADVANCED_OPTIMIZATIONS option will just ruin your code and your public API. Of course the solutions are at hand, but the question is if they worth the effort.

Read the rest of this entry »

March 11th, 2010 by radu

Follow me on twitter @extjslog. I will be tweeting on JavaScript, ExtJS, jQuery and other web 2.0 things.

PS: I am preparing the promised post on Google Closure Compiler ADVANCED_OPTIMIZATIONS.

Posted in News | No Comments »