<?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; ExtJS</title>
	<atom:link href="http://www.jslog.com/category/extjs/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>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>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>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>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>
		<item>
		<title>&#8220;Live&#8221; event in ExtJS</title>
		<link>http://www.jslog.com/live-event-in-extjs</link>
		<comments>http://www.jslog.com/live-event-in-extjs#comments</comments>
		<pubDate>Mon, 08 Feb 2010 21:45:38 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[ExtJS events]]></category>
		<category><![CDATA[live event]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=121</guid>
		<description><![CDATA[A quick intro to the live event in ExtJS, using delegates. It is similar to the jQuery live event, but much more powerful. This article provides a quick and useful insight into it.]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>One of the things I really liked about jQuery was the <a href="http://api.jquery.com/live/">&#8220;live&#8221; event</a>.<br />
The jQuery documentation explains it very straightforward: </p>
<blockquote><p>[with a live event you] <b>attach a handler to the event for all elements which match the current selector, now or in the future</b></p></blockquote>
<p><span id="more-121"></span><br />
I wanted to have something similar in ExtJS, and, no surprise, Ext has it, but it&#8217;s not very obvious for a newcomer.</p>
<p>
In jQuery you can easily say:</p>
<pre class="prettyprint">
$('p').live('click', function(){
    // do something on paragraph click
})
</pre>
<p>As it turns out, the &#8220;live&#8221; event in ExtJS is even more powerful and customizable.<br />
In ExtJS, the equivalent of the above is:</p>
<pre class="prettyprint">
Ext.getBody().on('click', function(event, target){
        // do something on paragraph click
    }, null, {
        delegate: 'p'
    })
</pre>
</p>
<p>
For more options and configuration parameters, see <a href="http://www.extjs.com/deploy/dev/docs/?class=Ext.Element" target="_blank">Ext.Element::addListener API</a> (Ext.Element.on() is a shorthand for the Ext.Element.addListener() method)
</p>
<p>As can easily be seen, you can add live events not only to the <b>body</b> element, but to any element.</p>
<pre class="prettyprint">
Ext.get('header').on('click', function(){
           //only handle anchors with the "menu" css class,
           //which are in the element with id="header"
     }, this /* the scope */, {
         delegate: 'a.menu'
    })
</pre>
<p>You can further distinguish between the target elements in the event callback</p>
<pre class="prettyprint">
Ext.get('header').on('click', function(e,target){
         //an anchor with class="menu" has been clicked in
         //an element with id="header"

         // Ext.Element.is(selector) tests the current
         // item for the given selector

         // target is of type HtmlElement, not Ext.Element,
         // so wrap in Ext.get()
         if (Ext.get(target).is('.item')){
             // do smth special with anchors with "item" class
         }
     }, this /* the scope */, {
         delegate: 'a.menu'
    })
</pre>
</p>
<p>You can see a <a href="http://www.jslog.com/demos/live_event.html" target="_blank">live demo here</a>. Thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/live-event-in-extjs/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Object oriented JavaScript with ExtJS</title>
		<link>http://www.jslog.com/object-oriented-javascript-with-extjs</link>
		<comments>http://www.jslog.com/object-oriented-javascript-with-extjs#comments</comments>
		<pubDate>Sat, 23 Jan 2010 20:49:47 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[object oriented javascript]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=97</guid>
		<description><![CDATA[This article explains how you can achieve powerful object oriented JavaScript with the help of ExtJS Core library. Good points on inheritance, overriding, flexibility, possible pitfalls that come with this approach. A good way to start building one page JavaScript web applications.]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been working a lot with ExtJS and I thought it&#8217;s good to share my experience. In this post I will explain how you can achieve object orientation with the help of <a href="http://www.extjs.com/products/extcore/?ref=family">ExtJS Core</a>, how easy it can be and some of its pitfalls.<span id="more-97"></span><strong> Learn by example</strong></p>
<pre class="prettyprint">
Ext.ns('myapp.cars');

(function(){
    var Car = Ext.extend(Object,{
	color: 'red',
	description: {
	    gears: 4,
	    year: 1980
	},

	constructor: function(config){
	    console.log("car constructor");
	    Ext.apply(this, config)
	},

	getColor: function(){
	    return 'actual color ' + this.color;
	},

	getMake: function(){
	    throw 'unimplemented method';
	}
    })

    myapp.cars.Car = Car;
})()

// ---- another file here: myapp.cars.Bmw.js
Ext.ns('myapp.cars');

(function(){

    var BmwCar = Ext.extend(myapp.cars.Car,{

	color: 'blue',

	constructor: function(config){
	    BmwCar.superclass.constructor.apply(this, arguments)
	},

	getMake: function(){
	    return "This is a BMW"
	}
    })

    myapp.cars.Bmw = BmwCar;
})()
</pre>
<p>First of all notice</p>
<pre class="prettyprint">
(function(){
     // your code here
})()
</pre>
<p>
We never want to populate our global &#8220;namespace&#8221; of JavaScript objects. So, we put all our code in a anonymous function, which is not only defined, but also executed. We will export only what&#8217;s needed, that is, the public API of our app.<br />
Second, notice</p>
<pre class="prettyprint">
Ext.ns('myapp.cars');
</pre>
<p>outside of our anonymous-function-that-hides-it-all. It is a shorthand for Ext.namespace. What it does is the following: it creates an object <code>myapp</code>, if it doesn&#8217;t exist. Then, it creates a property on this object (the newly created or the existing one) named <code>cars</code>, only if it doesn&#8217;t exist. I recomend putting a call to <code>Ext.ns('...')</code> at the beginning of every js file, and then, in the anonymous function call, attach what you need to into this public namespacing object. So all your files should look something like</p>
<pre class="prettyprint">
Ext.namespace('myapp.package.subpackage');
(function(){
    var MyClass = // class definition
    ....
    // end of class definition

    //in this way we "export" MyClass to be visible publicly
    myapp.package.subpackage.MyClass = MyClass
})()
</pre>
<p>Now let&#8217;s see our class hierarchy. Use <code>Ext.extend</code> to extend from an existing Object. If you don&#8217;t have a specific superclass you want to extend, just extend Object. Then, as a second parameter, provide an object literal, which can contain properties and/or functions. All these properties/functions will be placed in the prototype of your newly created class, overriding (if it is the case)  the properties in the prototype of the base class. Notice Ext has a special function, named <b>constructor</b>, which is called when objects are instantiated. If you define a constructor in the subclass, <b>don&#8217;t forget to call the superconstructor of the base class</b> (if you want &#8211; and probably you do).</p>
<pre class="prettyprint">
constructor: function(config){
   BmwCar.superclass.constructor.apply(this, arguments)
}
</pre>
<p>Notice how methods from the base class are called: &lt;current_class&gt;.superclass.&lt;method_name&gt;.apply(this, arguments). You could also call it with <b>call</b> and other arguments, but in this way, you just forward the existing arguments, whithout having to explicitly name them.<br />
In this example, in the constructor of the Car class we use a very powerful feature in JavaScript and ExtJS, dynamically applying properties to objects</p>
<pre class="prettyprint">
constructor: function(config){
    console.log("car constructor");
    Ext.apply(this, config)
},
</pre>
<p>Take all the properties given in the config and apply them to the car object. For instance, you could have a code like:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw({
	color:'black',
	getColor: function(){
	    return "my custom color";
	}
});
</pre>
<p>Not only does Bmw overrides the color attribute for the car, but this bmw instance in particular overrides the color attribute to &#8216;black&#8217;. Also override the <b>getColor</b> method. This gives a tremendous flexibility, allowing more than one level of overriding! Subclass overrides superclass, and object instance(of subclass) overrides subclass. So basically you can end up building custom bmw instances, each having it&#8217;s own implementation of getColor. Generally you won&#8217;t do method overriding at instance level, but you will want to override values in the properties of an instance. So calling your constructor with a config object is very useful when wanting to set values of multiple fields at once. </p>
<p>Another interesting feature is overriding a method at instance level, and also <b>using the previous implementation of the method</b>. Take a look:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw({
	color:'black',
	getColor: function(){
	    console.log('getColor: ');
            //use previous implementation - notice apply
	    return myapp.cars.Bmw.prototype.getColor.apply(bmw) + ' custom color';
	}
});
</pre>
<p>Notice the call to the <b>getColor</b> method from the prototype of the Bmw class, applied to the current instance, in order to keep the context of the method call.<br />
All these features of <b>prototypal inheritance</b> with JavaScript in general and ExtJS in particular, allow a great flexibility and many levels of customization.<br />
<br />
To recap, don&#8217;t forget that when you override a method, if you want to use the implementation in the base class, you have to use something like:</p>
<pre class="prettyprint">
 var BmwCar = Ext.extend(myapp.cars.Car,{
    getMake: function(){
        //use implementation in the superclass and forward any arguments
        BmwCar.superclass.getMake.apply(this, arguments)
    }
})
</pre>
<p>where <b>superclass</b> is a property set by <b>ExtJS</b> when creating the class, for easy reference to the superclass.</p>
<h2>Pitfalls</h2>
<p>There are some pitfalls you should be aware of. These appear because of the nature of the prototypal inheritance.<br />
Don&#8217;t forget that when you write:</p>
<pre class="prettyprint">
var subclass = Ext.extend(MySuperclass, {
    property1: value1,
    property2: value2,
    method1: function(){ ... },
    method2: function(){ ... }
});
</pre>
<p>all the properties of the config object given as the second argument to the <b>Ext.extend</b> function go into the prototype of the subclass. Let&#8217;s have some examples to see what can happen. Suppose for this example the myapp.cars.Car implementation above and the following Bmw implementation:</p>
<pre class="prettyprint">
var BmwCar = Ext.extend(myapp.cars.Car,{
	model: {
	    name: 'sedan'
	}
})
</pre>
<p>Now make the following tests:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw();
var secondBmw = new myapp.cars.Bmw();

secondBmw.color = "orange";
secondBmw.model = { name: 'hatchback'}

//typical behavior
console.log(bmw.color); // outputs "red"
console.log(bmw.model); //outputs Object { name="sedan"}
</pre>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw();
var secondBmw = new myapp.cars.Bmw();

//NOTICE change of model name also affects the first bmw instance
secondBmw.model.name = 'hatchback'
console.log(bmw.model); //outputs Object { name="hatchback"}
</pre>
<p>So we modify the model.name attribute on the secondBmw and it gets propagated to the first bmw instance. Why? Well, the <b>model</b> object belongs to the prototype of the Bmw class, so <b>it is shared between all the bmw instances</b>. Any change in properties of this object affects all instances of the class!<br />
But notice in the first test, changing the <b>model</b> object doesn&#8217;t affect all instances of Bmw. This is because the instruction</p>
<pre class="prettyprint">
secondBmw.model = { name: 'hatchback'}
</pre>
<p>changes the <b>model</b> property on the secondBmw instance to refer to a whole new object, independent of the class prototype. <br />
So you have to be warned. It&#8217;s <b>okay to put in the prototype properties which are JavaScript primitive types</b> (strings, numbers), but you have to take <b>special care when dealing with objects</b>! They are allowed, but you should be aware of the facts explained above and handle with care.</p>
<p>This is a summary of prototypal JavaScript inheritance with ExtJS. Play with it, try it, use it!<br />
Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/object-oriented-javascript-with-extjs/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

