Sencha Inc. | HTML5 Apps

Miscellaneous FAQ

Published Sep 17, 2010 | The Sencha Dev Team | FAQ | Medium
Last Updated Jul 11, 2011

This FAQ is most relevant to Ext JS, any version.

This article is currently due for review
We suspect that this article may be out-of-date or contain incorrect information.
But we are constantly editing articles, so we promise we will get to this one soon.

Find a Plugin by id

  • Include the following code, specify a pluginId, and use getPlugin('myPluginId').
Ext.Component.extend({
    getPlugin: function(pluginId) {
        if (Ext.isArray(this.plugins)) {
            for (var i = 0, len = this.plugins.length; i < len; i++) {
                if (this.plugins<i>.pluginId === pluginId) {
                    return this.plugins<i>;
                }
            }
            return false;
        } else {
            return this.plugins.pluginId === pluginId ? this.plugins : false;
        }
    }	
});

Automatically reload store

  • Option 1
dataStoreGrid = new ...
Grid = new ...
 
var t = setInterval('gridRefresh()',50000);
 
function gridRefresh{
   dataStoreGrid.reload();
}
  • Option 2
Ext.override(Ext.data.Store, {
    //    startAutoRefresh : function(interval, params, callback, refreshNow){
    startAutoRefresh: function(c){
        if (c.refreshNow) {
            this.load({
                params: c.params,
                callback: c.callback
            });
        }
        if (this.autoRefreshProcId) {
            clearInterval(this.autoRefreshProcId);
        }
        //use reload for subsequent refreshes
        //pass empty arguments so lastOptions is maintained
        this.autoRefreshProcId = setInterval(
            this.reload.createDelegate(this, []), c.interval * 1000);
    },
    stopAutoRefresh: function(){
        if (this.autoRefreshProcId) {
            clearInterval(this.autoRefreshProcId);
        }
    }
}); 
 
//typical store loading
store.load({
    params: { //parameters for the FIRST page load,
        start: 0, 
        limit: 10
    },
    scope: this,
    callback: function(rec, options, success){
        console.info(arguments);
    }
}); 
 
//load store with auto refresh
store.startAutoRefresh({
    refreshNow: true, //true to load store immediately
    interval: 20, //refresh rate in seconds
    params: { 
        start: 0, 
        limit: 10
    },
    scope: this,
    callback: function(rec, options, success){
        console.info(arguments);
    }
});

Invalid Label (Json)

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

Change background image

  • Dynamically change background image for panel
myPanel.body.setStyle('background-image', 'url(foo.png)');

Handling Single and Double Click at same time

el.on({
    click: {
        fn: function(){
            if (el.stopClickEvent) {
                el.stopClickEvent = false;
            }
            else {
                alert('click');
            }
        },
        //(assuming the mouse double-click timeout isn't set higher than 250ms)
        buffer: 250
    },
    dblclick: function(){
        el.stopClickEvent = true;
        alert('dblclick');
    }
});

Inserting an image into application

var image = new Ext.BoxComponent({
    id: 'id-of-component',
    autoEl: {tag: 'img', src: '...'}
});
//to update image source use:
Ext.getCmp('id-of-component').getEl().dom.src = 'newurl.gif';
//or if there's an extra parent element use:
Ext.getCmp('id-of-component').el.dom.firstChild.src = 'newurl.gif';

Creating a Button using an Image

Have your own image that you just want to behave like a button? Try this:

{
  xtype: 'box',
  autoEl: {tag: 'a', href: '#', children: [{tag: 'img', src: '...'}]},
  style: 'cursor:pointer;',
  listeners: {
    render: function(c) {
      c.getEl().on('click', function() {
        ...
      }, c, {stopEvent: true});
    }
  }
}

Defaults

  • defaults are applied to the items and not to the container.
var w = new Ext.Window ({
  width: 600,
  height: 500,
  id: 'w',
  title: 'prova',
  closable: false,
  layout:'border',
  defaults: {
    autoScroll: true,
    collapsible: true,
    split: true,
    bodyStyle: 'padding:15px'
  }, ....
  • This applies autoScroll, collapsible, split and bodyStyle to all items in the window (=regions of the border layout).
  • Defaults always get applied to components, but only to config objects if the option is not specified, e.g. panel1 will be autoScroll:false, but panel2 will be autoScroll:true.
defaults: {
  autoScroll:true
},
items: [{
  id: 'panel1',
  autoScroll: false
},new Ext.Panel({
  id: 'panel2',
  autoScroll: false
}]
  • defaults do not have precedence over options in config objects (e.g. panel 1).
  • defaults do have precedence over options in components (e.g. panel 2).

Capturing Events to Firebug Console

  • To capture events and log them in Firebug's console cut, paste, and execute this code block in firebug's console:
// to capture ALL events use:
Ext.util.Observable.prototype.fireEvent = 
    Ext.util.Observable.prototype.fireEvent.createInterceptor(function() {
        console.log(this.name);
        console.log(arguments);
        return true;
});
 
// to capture events for a particular component:
Ext.util.Observable.capture(
    Ext.getCmp('my-comp'),
    function(e) {
        console.info(e);
    }
);

How to make a Window fixed position when page scrolls

  • How to make a Window fixed position when page scrolls
var win = new Ext.Window({
    title: 'Test',
    x: 100,
    y: 100,
    width: 100,
    height: 100
});
win.show();
 
Ext.EventManager.on(window, 'scroll', function(){
    win.setPosition(100,
        (document.documentElement || document.body).scrollTop + 100);
}, window, {buffer: 50});
 
/*
IE7 w/o DocType specified document.documentElement.scrollTop 
will be 0 unless overflow:scroll.  To fix this replace the 
statement:   
 
(document.documentElement || document.body).scrollTop 
 
with:
(document.body || document.documentElement).scrollTop;
 
*/

Tooltips

  • How do Ext.QuickTips work?
  • If you have a html file with
<input type="button" value="OK" ext:qtip="This is a quick tip from markup!"/>

ExtJS automatically produces a tooltip when the mouse is over the button. (as long as you activate tooltips with Ext.QuickTips.init() at the beginning) When QuickTips initializes its tip, the initTarget method of Tooltip is called (QuickTips is an extension of ToolTip; reference src/widgets/tips/ToolTip.js). Target is document.body in this case. As it turns out, by adding a listener to body, the target returned by the event is the most concrete child rather the body itself.

Tools

Character Types from Various Languages

Make sure that all data is sent using a character set that supports your language ( UTF-8 is commonly preferred).

This includes:

  1. The .html pages.
<!-- In the head of page: -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- This does not make the html page UTF-8, you still
     have to store the html file in UTF-8 encoding -->
  1. The .js files (if you hard code any texts).
  2. JSON or XML data.

For dynamic files (.php, .jsp etc.) you should set the content type (e.g. Content-Type: text/html; charset=utf-8). See this cheat sheet for additional info. You might also need to change the configuration of your HTTP server and/or application server so it sends the correct content type for static files. For example an htaccess addcharset directive:

AddCharset UTF-8 .htm

You can check the content-type of every file using Firebug's Net tab:

Templates

Mess around with XTemplates on the Firebug console command line. You always need a <tpl> to process anything. for="." means the object being processed:

new Ext.XTemplate('<tpl for=".">{foo}</tpl>').apply({foo:'hello'})

<tpl>s can be nested to match the structure:

new Ext.XTemplate(
    '<tpl for=".">{foo}<tpl for="bar"> from {nested}</tpl></tpl>').apply({
        foo:'hello',
        bar: {nested: 'deeper'}
    })

KeyMap

  • Use this to disable the F5 key in IE6 (not tested on IE7) courtesy of Mystix. The basic idea is to fool IE (yes, IE is foolish indeed...) into thinking some other key was pressed.:
// disable F5 key in IE6 (doesn't work in Safari 3.2)
new Ext.KeyMap(document, {
    key: Ext.EventObject.F5,
    fn: function(keycode, e) {
        if (Ext.isIE) {
            // IE6 doesn't allow cancellation of the F5 key, so trick it into
            // thinking some other key was pressed (backspace in this case)
            e.browserEvent.keyCode = 8;
        }
        e.stopEvent();
    }
});
  • Capturing and collecting key presses. This script is intended to capture keypresses between "%" and "?" keys.
Ext.onReady(function(){
	var capture = false, result = [];
	Ext.getBody().on('keypress', function(e){
		var k = e.getKey();
		if(capture){
			if(k == 63){ // ?-key
				capture = false;
				alert(result.join(''));
			} else {
				result.push(String.fromCharCode(k));
			}
		}else if(k == 37){ // %-key
			capture = true;
			result = [];
		}
	});
});

411 Length Required

If the server is returning HTTP status 411, "Length required", this is because it is receiving a POST request for an operation which gets data.

The solution is to explicitly use the GET method. In almost all cases where requests are made to the server a method option is available.

Set height of ProgressBar

To make the inner elements size too, as of 3.3, the following extra is needed.

Ext.override(Ext.Element, {
    alignMiddle: function(parent) {
        if (Ext.isString(parent)) {
            parent = Ext.get(parent) || this.up(parent);
        }
        this.setStyle({
            'margin-top': (parent.getHeight() / 2 - this.getHeight() / 2) + 'px'
        });
    }
});
 
Ext.override(Ext.ProgressBar, {
    setSize: Ext.ProgressBar.superclass.setSize,
    onResize: function(w, h) {
        var inner = Ext.get(this.el.child('.x-progress-inner')),
            bar = inner.child('.x-progress-bar'),
            pt = inner.child('.x-progress-text');
            ptInner = pt.child('*');
            ptb = inner.child('.x-progress-text-back'),
            ptbInner = ptb.child('*');
        Ext.ProgressBar.superclass.onResize.apply(this, arguments);
        inner.setHeight(h);
        bar.setHeight(h);
        this.textEl.setHeight('auto');
        pt.setHeight('auto');
        ptb.setHeight('auto');
        ptInner.alignMiddle(bar);
        ptbInner.alignMiddle(bar);
        this.syncProgressBar();
    }
});
Share this post:
Leave a reply

Written by The Sencha Dev Team

1 Comment

paola

3 years ago

Dicten por favor, donde puedo leer sobre esto? 
http://www.b4yporn.com/ 
 
bubba

Leave a comment:

Commenting is not available in this channel entry.