<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>A Log on JavaScript</title>
	<atom:link href="http://www.jslog.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jslog.com</link>
	<description></description>
	<lastBuildDate>Thu, 21 Jul 2011 11:00:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Delayed function execution</title>
		<link>http://www.jslog.com/delayed-function-execution</link>
		<comments>http://www.jslog.com/delayed-function-execution#comments</comments>
		<pubDate>Thu, 21 Jul 2011 11:00:10 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[delayed]]></category>
		<category><![CDATA[function execution]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=265</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>I have written a small helper function to make delayed sequential function execution easier.</p>
<p>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.</p>
<p>So the code is the following:</p>
<pre class="prettyprint">
function runSequence(arr, scope, delay){
	arr.push(function(){});
	delay = delay || 0;

	var i = 0,
             len = arr.length;

	for(;i &#60; 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]();
}
</pre>
<p>We can do the following:</p>
<pre class="prettyprint">
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'}
 */
</pre>
<p>or the following:</p>
<pre class="prettyprint">
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
 */
</pre>
<p>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&#8217;m sure that there are other cases when this could prove useful.<br />
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.</p>
<p>Do you find this pattern useful?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/delayed-function-execution/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ExtJS Templates and formatting functions</title>
		<link>http://www.jslog.com/extjs-templates-and-formatting-functions</link>
		<comments>http://www.jslog.com/extjs-templates-and-formatting-functions#comments</comments>
		<pubDate>Fri, 25 Mar 2011 16:02:15 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[formatting]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=249</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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:</p>
<pre class="prettyprint">
new Ext.XTemplate('{0:plural("record","records")} deleted').apply([4])
// -> 4 records deleted
</pre>
<p>This is nice. Yet the formatting functions are not limited to just a few. Templates support all formatting functions in Ext.util.Format. What&#8217;s even better is that you can add your own formatting functions and have them in the templates.</p>
<p>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: &#8216;No records selected&#8217;, and not &#8216;0 records selected&#8217;; &#8216;One record selected&#8217;, and not &#8216;1 record selected&#8217;. So, a nice solution would be the following:</p>
<pre class="prettyprint">
(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 &#038;&#038; !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
    })
})();
</pre>
</p>
<p>I really think templates are very powerful, so use them! Any other clever usages? (besides all the ext4 being built on top of them <img src='http://www.jslog.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/extjs-templates-and-formatting-functions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No for loops &#8211; Number prototype instead</title>
		<link>http://www.jslog.com/loop-using-number-prototype</link>
		<comments>http://www.jslog.com/loop-using-number-prototype#comments</comments>
		<pubDate>Fri, 26 Nov 2010 17:19:02 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[function scope]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=233</guid>
		<description><![CDATA[Recently I got borred with the for loops and I added the &#8220;times&#8221; 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 */){
     [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I got borred with the for loops and I added the &#8220;times&#8221; 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:</p>
<pre class="prettyprint">
     (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);
</pre>
<p>Together with this, I&#8217;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: </p>
<pre class="prettyprint">
    var arr = [].concat(valueOrArray);
</pre>
<p>See below the source code.</p>
<pre class="prettyprint">/**
 * 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</pre>
<p>As for the performance, I have tested the <b>times</b> function against the for loop, and it seems to give about same results at a first glance. Any feedback on this?</p>
<p>P.S. Iterating over arrays gets even easier by adding an <b>'each'</b> function to the Array prototype. Adding to the prototype of standard JavaScript objects is a debatable practice, and should not be abused.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/loop-using-number-prototype/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>What I expect from ExtJS 4</title>
		<link>http://www.jslog.com/what-i-expect-from-extjs-4</link>
		<comments>http://www.jslog.com/what-i-expect-from-extjs-4#comments</comments>
		<pubDate>Sun, 12 Sep 2010 20:09:51 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[extjs4]]></category>
		<category><![CDATA[graphs]]></category>
		<category><![CDATA[ie6]]></category>
		<category><![CDATA[raphael]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[theming]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=225</guid>
		<description><![CDATA[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&#8217;t attend (there&#8217;s quite a distance from Cluj-Napoca, Romania to San Francisco), I am expressing here some opinions on what I think would be [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;t attend (there&#8217;s quite a distance from <a href="http://maps.google.ro/?ie=UTF8&amp;hq=&amp;hnear=Cluj-Napoca,+Cluj&amp;ll=46.800059,23.598633&amp;spn=8.153282,19.753418&amp;z=6" target="_blank">Cluj-Napoca, Romania</a> 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.</p>
<ol>
<li><strong>Keep the DOM small</strong>. 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&#8217;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.</li>
<li><strong>Drop IE 6 support</strong>. 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&#8217;s push at least for a minimum subset of it to be out there.</li>
<li><strong>Integrate </strong><a href="http://raphaeljs.com/" target="_blank"><strong>Raphael</strong></a><strong> graphs</strong>. 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&#8217;s mention it upfront, just in case. It&#8217;s nice to have charting, but Flash is not the best sollution.</li>
<li><strong>Give us an integrated test platform</strong>. Testing is important, but we don&#8217;t see it so often in our own ExtJS apps. Yes, <a href="http://www.jslog.com/testing-extjs-with-selenium-automating-ui-tests" target="_blank">we test with Selenium</a>, 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 <a href="http://developer.yahoo.com/yui/3/test/" target="_blank">YUI Test</a> framework. Would be nice if they shared it, so we can all benefit.</li>
<li><strong>Custom theming</strong>. This is a well known issue, but let&#8217;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 <a href="http://jqueryui.com/themeroller/" target="_blank">jQueryUI theme roller</a>. Let&#8217;s face it, on this issue, jQuery is far more attractive. I didn&#8217;t like to say it, but that&#8217;s the truth. With the help of a designer I have put up a custom theme, and yes&#8230;. you have a bit of headache. It&#8217;s not like you&#8217;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.</li>
<li><strong>Distribution builder</strong>. 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&#8217;s hope we&#8217;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 &#8216;<strong>xtype</strong>&#8216; 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.</li>
</ol>
<p>These are not all the issues that would be nice to have, but at least the most important that come to mind. It&#8217;s nice to see the ExtJS ecosystem at work and new components popping up, like the pivot grid, the calendar etc.</p>
<p>So&#8230; 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!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/what-i-expect-from-extjs-4/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Testing ExtJS with Selenium &#8211; Automating UI Tests</title>
		<link>http://www.jslog.com/testing-extjs-with-selenium-automating-ui-tests</link>
		<comments>http://www.jslog.com/testing-extjs-with-selenium-automating-ui-tests#comments</comments>
		<pubDate>Wed, 14 Jul 2010 17:00:33 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=217</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.
</p>
<p>
Instead, <b>Selenium tests for ExtJS should rely on CSS selectors</b>. For every button, grid, label, tab or any significant UI element, I simply chose to use the <strong>cls</strong> attribute and specify a CSS class.</p>
<pre class="prettyprint">
new Ext.Button({
    text: 'Ok',
    cls: 'seleniumOkButton', //can have more classes, separated by space
    scope: this,
    handler: function(){ ... }
})
</pre>
<p>This is how a basic button that is used in automation testing looks like. And I use the following XPath selector in Selenium:</p>
<pre class="prettyprint">
//table[contains(@class,'seleniumOkButton')]
</pre>
</p>
<p>Happy automated testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/testing-extjs-with-selenium-automating-ui-tests/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Function arguments</title>
		<link>http://www.jslog.com/function-arguments</link>
		<comments>http://www.jslog.com/function-arguments#comments</comments>
		<pubDate>Mon, 31 May 2010 09:32:17 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=209</guid>
		<description><![CDATA[Well, if you are programming in JavaScript for a while, you are familiar with the arguments &#8216;array&#8217; 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Well, if you are programming in JavaScript for a while, you are familiar with the <b>arguments</b> &#8216;array&#8217; 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 <b>arguments</b> 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&#8217;s <b>length</b> property. That&#8217;s all. What if you want to make a copy of the array? What if you want to push or pop items? Well&#8230; you have some work to do&#8230; OR &#8230;</p>
<p>Or do something smart. Like call the slice method from Array.prototype on the arguments, something like:</p>
<pre class="prettyprint">
//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)
</pre>
<p>Well, maybe most of you expert JavaScript programmers have thought about this, and this is not a news. But, let&#8217;s share from our experience to the more novice/newcomers to JavaScript and show them the beauty of this language! </p>
<p>JavaScript is a great language! It&#8217;s expressive! It&#8217;s powerful! That&#8217;s why we love JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/function-arguments/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Window &#8216;tofront&#8217; and &#8216;toback&#8217; events</title>
		<link>http://www.jslog.com/window-tofront-and-toback-events</link>
		<comments>http://www.jslog.com/window-tofront-and-toback-events#comments</comments>
		<pubDate>Wed, 26 May 2010 10:07:51 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS Components]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[overriding]]></category>
		<category><![CDATA[window]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=200</guid>
		<description><![CDATA[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 &#8216;tofront&#8217; and &#8216;toback&#8217; events. In an app I am working on, the user can have quite many windows [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8216;tofront&#8217; and &#8216;toback&#8217; 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 <strong>toFront</strong> method in <strong>Ext.Window</strong>. Below you can see the code, with some basic comments.</p>
<p><b>NOTE</b>: I know there are the <b>activate</b> and <b>deactivate</b> events on every window, but when a window triggers the &#8216;deactivate&#8217; event, <b>Ext.WindowMgr.getActive()</b> still returns it as the active window. This is why I needed the &#8216;tofront&#8217; and &#8216;toback&#8217; events.</p>
<pre class="prettyprint">
(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;
        }

    });
})();
</pre>
<p>I needed to run code both <strong>before</strong> and <strong>after</strong> the default implementation of the <strong>toFront</strong> method. If I didn&#8217;t need this, an easier approach would have been to use createSequence:</p>
<pre class="prettyprint">
Ext.override(Ext.Window,{
       toFront: Ext.Window.prototype.toFront.createSequence(function(){
             // code here.
       })
})
</pre>
<p>Nice ExtJs! Go try it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/window-tofront-and-toback-events/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ExtJS TextField that cannot start with whitespace</title>
		<link>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace</link>
		<comments>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace#comments</comments>
		<pubDate>Thu, 01 Apr 2010 11:43:32 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS Components]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[overriding]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[textfield]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=192</guid>
		<description><![CDATA[Recently I needed a text field in ExtJS that doesn&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I needed a text field in ExtJS that doesn&#8217;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.</p>
<p>Here is the code for this:</p>
<pre class="prettyprint">
(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 == ' ' &#038;&#038; (this.getCaretPos(this.el.dom) == 0) ){
                e.stopEvent()
            }

            //the case when the text is selected and the user presses space
            if (cc == ' ' &#038;&#038; 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);
        }
    })

})()
</pre>
<p>Hope it helps! Enjoy the code. If you have any questions, let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Google Closure Advanced Compilation</title>
		<link>http://www.jslog.com/google-closure-advanced-compilation</link>
		<comments>http://www.jslog.com/google-closure-advanced-compilation#comments</comments>
		<pubDate>Sun, 21 Mar 2010 21:24:10 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[Google Closure]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[js code optimization]]></category>
		<category><![CDATA[obfuscation]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=171</guid>
		<description><![CDATA[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 &#8211; not only renaming local variables and functions, but it renames GLOBAL variables and functions. In this way, it can [...]]]></description>
			<content:encoded><![CDATA[<p>As I have promised in <a href="http://www.jslog.com/using-google-closure-compiler">this</a> post, I am giving a review of the <code>ADVANCED_OPTIMIZATIONS</code> option in Google Closure JavaScript Compiler.</p>
<p>Beyond simply shortening variable names, Closure Compiler with ADVANCED_OPTIMIZATIONS, does three other important steps:</p>
<ul>
<li><b>aggresive renaming</b> &#8211; not only renaming local variables and functions, but it renames GLOBAL variables and functions. In this way, it can ruin your public API</li>
<li><b>dead code removal</b> &#8211; 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.</li>
<li><b>function inlining</b> &#8211; inserting the function&#8217;s body instead of the function call, where appropriate</li>
</ul>
<p>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.
</p>
<p><span id="more-171"></span></p>
<p>
<h3>Keep your public API</h3>
<p>If you provide ONLY the code below to Google Compiler, it produces <b>empty</b> output:</p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
</pre>
<p>What? Empty output? Well&#8230; yes, as you never call your function. Instead, for the next code: </p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
hello('jslog');
</pre>
<p>it produces the following output:</p>
<pre class="prettyprint">
alert("Hello jslog");
</pre>
<p>This is smart! But we want to preserve our API (by the way, in the tutorial for Google Closure Compiler Advanced Optimizations, <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html">Google says on this page</a> that the <code>hello</code> function is preserved, while it is NOT &#8211; see section <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html#removal">Removal of code you want to keep</a> and try the code online at <a href="http://closure-compiler.appspot.com/home">Closure Compiler UI Tool</a>)
</p>
<p>
So if the <code>hello</code> method above would be part of the public API, it would break third parties using it. Google proposes a solution for this: export the public objects/functions into the global namespace using the <code>window</code> object:</p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
hello('jslog');
window['hello'] = hello;

//and the output is:
function a(b){alert("Hello "+b)}a("jslog");window.hello=a;
//so the hello function is kept as a property on the global window object
</pre>
<p>Instead, if you use:</p>
<pre class="prettyprint">
window.hello = hello;
</pre>
<p>you get </p>
<pre class="prettyprint">
function b(c){alert("Hello "+c)}b("jslog");window.a=b;
</pre>
<p>which is surely not what you want. So make sure you use the <code>window['public_name']</code> notation. You should also standardize the way you access properties in your objects, either using the array notation, or the dotted notation, otherwise the compiler could be mislead by a mix of the two. But sometimes we just need to use both, as properties may be automatically generated at runtime.
</p>
<p>Other problems with the <b>Google Closure Compiler</b> <code>ADVANCED_OPTIMIZATIONS</code> are separately compiling blocks of code with dependencies to external JavaScript. The solution for this is </p>
<ul>
<li>using either <b>exports</b> like the above or with the <code>goog.exportSymbol()</code> or</li>
<li>using extern files specifically provided as a compilation option</li>
</ul>
<p>In any case, I think this is just a bit too clumsy. </p>
<p>Moreover, having a class and export all its properties/functions is quite a job to to if your app is already a large one. Just have a short example:</p>
<pre class="prettyprint">
MyClass = function(name) {
  this.myName = name;
};
MyClass.prototype.myMethod = function() {
  alert(this.myName);
};
window['MyClass'] = MyClass; // <-- Constructor
MyClass.prototype['myMethod'] = MyClass.prototype.myMethod; <-- export mechanism

//the above compiles to
MyClass=function(a){this.b=a};MyClass.prototype.a=function(){alert(this.b)};window.MyClass=MyClass;MyClass.prototype.myMethod=MyClass.prototype.a;
</pre>
</p>
<p>
<h3>Conclusions</h3>
<p>After this short overview of the <code>ADVANCED_OPTIMIZATIONS</code> flag, I really think most people won't need it. If you already have a large library, having it compiled with advanced optimizations would be a total nightmare, as it would require a review of all public methods and properties and additional work for each. And the gain? Just a few kilobytes. I have tried compiling <b>ExtJS Core with advanced optimizations and got aprox 62 KB</b>, while with <b>simple optimizations it is 74 KB</b>. Not very well for the amount of effort it would require, in my opinion. </p>
<p>But if you still think advanced optimizations is for you, you are probably wanting to optimize a lot, and you should first start seaching for other ways to optimize - first, make sure you combine all your js code into one file. It's better to have one js file of 100KB rather than have 10 files each of 5 KB. So make sure you are doing every other possible optimization before moving to the advanced optimizations flag.</p>
<p>After all, it's up to you to decide if it's worth the effort!
</p>
<p>PS: You can follow me on twitter <a href="http://twitter.com/extjslog">@extjslog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/google-closure-advanced-compilation/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Follow me on twitter</title>
		<link>http://www.jslog.com/follow-me-on-twitter</link>
		<comments>http://www.jslog.com/follow-me-on-twitter#comments</comments>
		<pubDate>Thu, 11 Mar 2010 07:35:45 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=182</guid>
		<description><![CDATA[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.
]]></description>
			<content:encoded><![CDATA[<p>Follow me on twitter <a href="http://twitter.com/extjslog">@extjslog</a>. I will be tweeting on JavaScript, ExtJS, jQuery and other web 2.0 things.</p>
<p>PS: I am preparing the promised post on Google Closure Compiler ADVANCED_OPTIMIZATIONS.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/follow-me-on-twitter/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

