<?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 &#187; quick tips</title>
	<atom:link href="http://www.jslog.com/category/quick-tips/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>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>Quick tip: use &#8220;scope&#8221; config option</title>
		<link>http://www.jslog.com/use-scope-config-option-quick-tip</link>
		<comments>http://www.jslog.com/use-scope-config-option-quick-tip#comments</comments>
		<pubDate>Wed, 24 Feb 2010 20:53:22 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[ExtJS events]]></category>
		<category><![CDATA[function scope]]></category>
		<category><![CDATA[functions]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=159</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<h2>You should make use of the <strong>scope</strong> config option in components</h2>
<p>.</p>
<ul>
<li>in Ajax calls
<pre class="prettyprint">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(){ .... }
}</pre>
<p>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 &#8216;window&#8217; object, which is not very useful. In the code above, we execute the success callback in the &#8216;this&#8217; scope, &#8216;this&#8217; being the instance of <b>MyPanel</b> which executes the <b>doSave</b> method. This is why we can safely call <b><code>this.onSuccess(response)</code></b>, as &#8216;this&#8217; is a MyPanel object, which has the onSuccess method.<br /> 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!
</li>
<li>in Buttons
<pre class="prettyprint">{
    xtype: 'button',
    text: 'Save',
    handler: function(){
	//do something on pressing the button
    },
    scope: myScope //scope of the handler
}</pre>
</li>
<li>with Stores
<pre class="prettyprint">new Ext.data.Store({
    //...other config options
    autoLoad: {
	callback: function(){ ... },
	scope: aScope //for the callback function after loading the store
    }
})</pre>
</li>
<li>in listeners
<pre class="prettyprint">new Ext.Panel({
    listeners: {
	scope: window, //the scope of all listeners in this config
	show: function(){ ... },
	afterrender: function(){ ...this is 'window' }
    }
})</pre>
</li>
<li>in <a href='http://www.extjs.com/deploy/dev/docs/?class=Ext.Action'>actions</a> </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/use-scope-config-option-quick-tip/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick tips on ExtJS and JavaScript</title>
		<link>http://www.jslog.com/quick-tips-on-extjs-and-javascript</link>
		<comments>http://www.jslog.com/quick-tips-on-extjs-and-javascript#comments</comments>
		<pubDate>Thu, 18 Feb 2010 19:45:04 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS Components]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[ExtJS]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=147</guid>
		<description><![CDATA[Tips on JavaScript and ExtJS: using the ExtJS ref config option on panels and other components.]]></description>
			<content:encoded><![CDATA[<p>I will usually try to post a major and well documented <b>article</b> on this blog <b>every week</b>. 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.</p>
<p>Here is the first one:</p>
<p>
<h2>Use the <b>ref</b> config option in ExtJS</h2>
<p><span id="more-147"></span></p>
<pre class="prettyprint">

var win = new Ext.Window({
    layout: 'fit',
    width: 300,
    height: 200,
    title: 'my window',
    items: [{
            <b>ref</b>: 'panel',
            xtype: 'panel', layout: 'form',
            frame: true, defaults: {xtype: 'textfield'},
            items: [
                {<b>ref</b>: '../nameField', fieldLabel: 'Name'},
                {<b>ref</b>: 'age', fieldLabel: 'Age'}
            ]
    }]
});

win.show();
//so now, with the above ref options, you can do:
win.nameField.setValue('name here');
win.panel.age.setValue(20);
</pre>
<p>Notice in the example above that setting ref <b>age</b> config puts a reference &#8220;age&#8221; in the panel containing the text field, while puting a ref <b>../nameField</b> sets a &#8220;nameField&#8221; reference on the component one more level up, that is, the containing window. In this way, you can navigate many levels, each &#8220;/&#8221; navigating one more level upwards.<br />
In this next example, I introduce another level of nesting, by artificially adding another panel, in order to illustrate the navigation with multiple slashes.</p>
<pre class="prettyprint">

var win = new Ext.Window({
    layout: 'fit',
    width: 300,
    height: 200,
    title: 'my window',
    items: [{
            ref: 'panel',
            xtype: 'panel', layout: 'form',
            frame: true, defaults: {xtype: 'textfield'},
            items: [

                {
                     xtype: 'panel', fieldLabel: 'Name', layout: 'fit',
                     items: [{xtype: 'textfield', ref: '//nameField'}]
                     //notice above, two slashes, which puts
                     //nameField reference on the containing window (two levels)
                },
                {ref: 'age', fieldLabel: 'Age'}
            ]
    }]
});

win.show();
win.nameField.setValue('name here');
win.panel.age.setValue(20);
</pre>
<p>Please see <a href="http://www.extjs.com/deploy/dev/docs/?class=Ext.Component&#038;member=ref">Ext.Component &#8220;ref&#8221; reference</a> from the Ext API.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/quick-tips-on-extjs-and-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

