July 14th, 2010 by radu

Automation testing of UI interfaces 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 »
February 24th, 2010 by radu

You should make use of the scope config option in components

.

  • in Ajax calls
    var MyPanel = Ext.extend(Ext.Panel, {
        doSave: function(){
    	Ext.Ajax.request({
    	    url: 'your_url',
    	    params: ....
    	    success: function(response){
    		response = Ext.decode(response.responseText);
    		this.onSuccess(response)
    	    },
    	    scope: this //the scope in which the success callback is called
    	})
        },
        onSuccess: function(){ .... }
    }

    In this example, specifying the scope is very useful. By default, the success callback on Ajax calls is executed with the scope being the browser ‘window’ object, which is not very useful. In the code above, we execute the success callback in the ‘this’ scope, ‘this’ being the instance of MyPanel which executes the doSave method. This is why we can safely call this.onSuccess(response), as ‘this’ is a MyPanel object, which has the onSuccess method.
    I find the scope config property very useful, so even though specifying the scope of a function is very natural in JavaScript, the fact that ExtJS made it so natural and easy deserves being noted. Well done ExtJS!

  • in Buttons
    {
        xtype: 'button',
        text: 'Save',
        handler: function(){
    	//do something on pressing the button
        },
        scope: myScope //scope of the handler
    }
  • with Stores
    new Ext.data.Store({
        //...other config options
        autoLoad: {
    	callback: function(){ ... },
    	scope: aScope //for the callback function after loading the store
        }
    })
  • in listeners
    new Ext.Panel({
        listeners: {
    	scope: window, //the scope of all listeners in this config
    	show: function(){ ... },
    	afterrender: function(){ ...this is 'window' }
        }
    })
  • in actions
February 18th, 2010 by radu

I will usually try to post a major and well documented article on this blog every week. But during the week, I will also have smaller tips, just a few lines short, about small things/improvements that can make your life better using JavaScript and ExtJS.

Here is the first one:

Use the ref config option in ExtJS

Read the rest of this entry »

February 8th, 2010 by radu

jQuery is a nice JavaScript library, we all know it. But not many of us are familiar with ExtJS. As I have now been working with both, I needed some time to adapt to the change from jQuery to ExtJS and rediscover how things are done the easiest way with both libraries.

One of the things I really liked about jQuery was the “live” event.
The jQuery documentation explains it very straightforward:

[with a live event you] attach a handler to the event for all elements which match the current selector, now or in the future

Read the rest of this entry »

January 30th, 2010 by radu

This is a good news for all web developers. As I am using Google Apps, I have just received an email from Google stating that they will not support IE6 any longer in their apps. Well… finally a big player had the courage to make IE6 history! To give you a bit more detail about what Google is going to do, here is a quote from their email:

Over the course of 2010, we will be phasing out support for Microsoft Internet Explorer 6.0 as well as other older browsers that are not supported by their own manufacturers.

We plan to begin phasing out support of these older browsers on the Google Docs suite and the Google Sites editor on March 1, 2010. After that point, certain functionality within these applications may have higher latency and may not work correctly in these older browsers. Later in 2010, we will start to phase out support for these browsers for Google Mail and Google Calendar.

Google Apps will continue to support Internet Explorer 7.0 and above, Firefox 3.0 and above, Google Chrome 4.0 and above, and Safari 3.0 and above.

We will certainly not miss you, IE6!
Waiting for comments from happy developers!

Tags: , ,
Posted in News | No Comments »