JSON or XML intermediate data format

You might or might not have heard about XML and JSON. And wonder which one is better to represent data with for communication, save functionality or config.

Before I do so I will explain what JSON and XML are in depth. If you are not interested, skip to ‘One over the other’

What is JSON?
JSON stands for JavaScript Object Notation and is actual javascript code. When put in to a javascript evaluator JSON can directly be translated in to objects, array and primitive types (integer, string, float).

A basic JSON string containing a person object could look like this:

name: ‘John’,
age: 14,
length: 1.55,
profession: ‘Student’,
friends: ['Suzzy', 'Cate', 'Mike', 'Tom']

Although JSON can only be parsed when well formed. Their is no default possibility to define what every value should look like. If you want to put ‘hello world’ into the length property this is valid. To do such checks code should be written to check these properties.

As noted before that JSON is actual javascript code. So parsing of these string is in general very quick.

What is XML?
XML stands for Extensible Markup Language and has been standardized by the W3C (World Wide Web Consortium). And has been created to standardize the way HTML (HyperText Markup Language) is written.

The same object shown above could look like this.


I would like to point out that this representation automatically makes ‘objects’ from friends. Make it easier to put more properties on these. But the same can be done in JSON. So far you can represent the same complexity of data.

XML however has 2 things that make it more powerful then JSON.

First off is XSD (XML Schema Document) can be used to validate the structure and data types (not if it’s well formed, because it needs to be well formed to be able to check it against an XSD). XSD are XML’s with tight regulation on how they should be build and describe how your XML should look like. Thus using an XSD makes it very easy to pinpoint troubles in your data structure as it will give an accurate error of the problem.
For further information check: http://www.w3schools.com/schema/default.asp

Second is XSLT (EXtensible Stylesheet Language) which can be used to format a XML to more readable formats. Although only text can be produced by default, like HTML pages or txt files. This format is also tightly standardized and is being used as a base for PDF generators and other formats.
Check http://wiht.link/XSLT-intro/ for more information.

Finally I would like to point out that XML needs some getting used to when first used to write a data structure for. With JSON objects and arrays explain themselves. Defining structures comes naturally as it is clear what every part does.
With XML it might not always be clear how something should be represented at first and some research is needed. This is especially true when using XSD or XSLT documents.

One over the other
Here under I will point out the strengths and weaknesses of both formats.

Using JSON over other interchange-formats

  • Can be read more quickly
  • Little overhead
  • Fast writing
  • Easier to learn
  • High performance deserializing


  • Needs time getting used to
  • If you write your own JSON parser its hard to debug
  • Harder to cut in to chunks

Thoughts on XML

  • Better error handling on syntax errors
  • More easily readable with deep levels
  • Superiour data integrity checking when XSD is used
  • XSLT can be used to formating for readability


  • To make error handling work their is need to make a XSD
  • Overhead with closing tags (slows down reading too)
  • Chance of conflicting names and functions of nodes
  • Necessity to create well formed XML constructions to represent your data
  • Harder to learn when structures become more complex

Although you might be dazzled or tempted to choose one over the other. I would like to point out that neither is absolutely superior and either can be used for all purposes you might have to represent data. However one is more suited for certain applications then the other.

If you have a website with lose data calls and no refresh, use JSON. It’s faster and has less overhead. In this fashion JSON is suitable for other communication and cases you need small size and high decoding speed.

If you need readability and tight error control over large sets of data that are being maintained by people. Use XML. It’s XSD data integrity checking makes it far easier to write by hand and XSLT can speed up human checking. So it’s ideal for config files, documents and dumps of large chunks of data that are complex in nature.

ExtJs 3.4 – Using tooltips

Tooltips provide an easy way to add useful information without cluttering the screen with enourmass chunks of data. ExtJs has fitted a couple of elements with a default tooltip. Button, Grid.Column.Header and Window are examples of that.

But sometimes you find yourself wanting to emphasize other things like a grid, rows, grid cells, an icon or blocks of text.

There is qtip, which can be placed within the HTML code directly to provide the user with a simple tooltip. But you have to encode everything to not make the first “ or ‘ break it.

So I recommend using the tooltip class.

Basic tooltip

This will set a tooltip on any element with the CSS class “tooltip-target” that is within the the panel “this.mainPanel”.

The CSS class does not have to exist for this to work. You might however want to add an empty CSS class with a comment, just to be sure it doesn’t get cleaned out by accident by someone that stumbles upon it.

var tip = new Ext.ToolTip({
   target: this.mainPanel.getEl(),     //target to apply tooltip on (also scope of the search, MUST be an Ext.element)
   delegate: '.tooltip-target', //target the tooltip will be shown on
   delay: 0,                   //how long to hover before showing
   trackMouse: false,          //follow the pointer while over element
   renderTo: document.body,    //where to draw, document.body is recommended
   autoHide: false,            //don’t hide after a while
   anchor: "right",            //where to show the arrow on the tooltip
   html: "Tooltip content"     //content to show

Grid cell

To make it work on a grid, just provide a different delegate and target. This will popup when hovering a row. If you want to make it select on just some cells, make up your mind in the renderer, by adding the previously mentioned “.tooltip-target” as delegate.

var gridTip = new Ext.ToolTip({
   target: this.grid.getView().mainBody,
   delegate: '.x-grid3-row',
   renderTo:  document.body,
   html: "Tooltip content"

Updating the content from given element

Nice, but now I got fixed content within the tooltip, making it hard to use. You first thought might be: “I could make more CSS classes to hang other tooltips from .”

Consider that every tooltip will be activated when entering the scope of its target elements. This could create a performance hit.

Instead update the content of the tooltip with the element you just hovered over. Is most cases like with a grid the data that the element you hovered over originated from is in a store. Or more precise, inside a record.

So for a grid you could use this after creating the tooltip.

gridTip.on("beforeshow", function(tip) {
   //the element being hovered over
   var triggerElement = tip.triggerElement;            

   //get row index
   var rowIndex = this.grid.getView().findRowIndex(triggerElement);

      //get record
      var record = this.grid.getStore().getAt(rowIndex);

      //you could also format this
      //or use another store to add even more information
      var content = record.get(“some-column”);

      //update the tooltip
}, this);

Update tooltip with call

As long as the function is delayed, the tooltip will not be shown. So it is a good practice to add a loading message and update the tooltip as soon as data from example an AJAX call is available.

ExtJs 3.4 – Using XTemplate – Basics

ExtJs has a whole range of useful components, but sometimes a more appealing interface object is required or one that is lighter to render. ExtJs provides you with a function that makes it easier to basically make anything you want within the limits of HTML and CSS.

Traffic light example
For this article I will use a component we use to illustrate risk within our application in the form of a traffic light. I will extend this example step by step to give you an idea how to design a control from the ground up and give you a feeling on how easy it can be.

If you are searching for more in dept information about how to create any kind of control try “Using XTemplate – Advanced” article.

Note: I will declare all variables in global space to make the example easier to read and try out. Using it like this is strongly discouraged as it will NOT provide any data layer abstraction. So when you got 1000+ variables inside your applicition, you are bound to override one that is used by another part of the application. When I got the time I will provide you with an article that explains this more in dept and provides you with solutions.

Setup XTemplate: Hello world
This example will output an Ext.Window that shows hello world as content.

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   template: new XTEmplate('Hello world'),
   data: {}


I agree, you can achieve the same with the HTML tag or by adding an element with that text. So lets make it more dynamic.
Now add message: ‘hello this world’ to the data object and replace hello world in the template with {message}

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   template: new XTemplate('{message}'),
   data: {
       message: "Hello this world"


Now the message shown is read from the data object provided. This works because this behavior is inherited from Ext.Component. When tpl and data are provided, it will attempt to fill the given element with these 2 variables on render.

Now their are 2 ways to move forward. You can either call overwrite on the tpl, supply the target and data directly or call update on this component by providing the data needed. I will show you both. But first we need to split off the data object, because in a window the property ‘data’ it is not available after render. This while we want it to know what the previous state of the window was.

trafficLightData = {
   message: "Hello this world"

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   template: new XTemplate('{message}'),
   data: trafficLightData


Call update on component
There, now the easiest way is the following which uses the internal update function to handle the request.

trafficLightData.message = "Goodbye and thank you for all the fish";

Call overwrite on the template
Although the following example is more ‘difficult’ and does not provide extra functionality in this example. I would like to show it to you because you can use it to apply one template to multiple components. Because it uses element as a target you can apply a template to Objects that are not inherited from Component.

trafficLightData.message = "Goodbye and thank you for all the fish";
trafficLight.tpl.overwrite(trafficLightData.body, trafficLightData);

In short what I do is call overwrite on the Template, the same method used by update(), but provide the target myself. Which is Window.Body, the element that shows the content part of a Window.
Note that this only works when the Window is rendered as the body element is created then.

Example adaptive render
Now this does not at all look like a traffic light. So let’s change that.

trafficLightData = {
   color: "red"

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   tpl: new Ext.XTemplate(
', '
', '
', '
' ) }) trafficLight.show();

Wow, what is all this?
Well first is the template: When you keep adding string as parameters, these will be appended to the template. So this makes it a lot more readable. Then I have added 3 bullets using HTML entity • • and put them in to div as the conveniently puts them on new lines.

Next, let’s make the component show the actual value, which is red as shown in trafficLightData.

trafficLightData = {
   color: "red"

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   tpl: new Ext.XTemplate(
font-size: 20px;"•
', '
font-size: 20px;">•
', '
font-size: 20px;">•
', '
' ) }) trafficLight.show();

Now this is one of the more interesting things of a template. When is used, you can add logical expressions, loops and functions in the template. In this example I use IF. Now inside the if attribute I have put “color==\’red\’”.
When a value is not inside ” it is seen as a variable that it will try to get from the data object. When put between ” it becomes a string you can use to compare. So this is essentially a simple if construction, that adds ‘ font-size: 20px;’ to the style attribute of the div when true.

Example click events
Now it makes the red light show up on default, but we want it to change dynamically, on click for example. So let’s do that first.

trafficLightData = {
   color: "red"

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   tpl: new Ext.XTemplate(
font-size: 20px;">•
', '
font-size: 20px;">•
', '
font-size: 20px;">•
', '
' ), colorSwitch: { red: "green", orange: "red", green: "orange" } }) trafficLight.on("afterrender", function() {     trafficLight.body.on('click', function(){         trafficLightData.color = trafficLight.colorSwitch[trafficLightData.color];         trafficLight.update(trafficLightData);    }, this); }, this); trafficLight.show();

Although not very elegant this will make the traffic light switch from red -> green -> orange -> red. This is achieved by making an event click on Window.body which is created after render of the Window. Then the colorSwitch object is used to retrieve the next value. Then update() is called with the updated value.

Now to make a more useful component out of this you probably want to click the color you would like to select and be able to retrieve it.

This requires the following, you need to know which element has been clicked. You can make a listener for every rendered element, but this is heavier and in my opinion not a very nice solution. Instead we introduce our own attributes on the rendered elements. And let this same event return the element that was clicked.

trafficLightData = {
   color: "red"

trafficLight = new Ext.Window({
   height: 100,
   width: 100,
   tpl: new Ext.XTemplate(
font-size: 20px;">•
', '
font-size: 20px;">•
', '
font-size: 20px;">•
', '
' ) }) trafficLight.on("afterrender", function() {     trafficLight.body.on('click', function(fEvent, fHtmlElement, fOption object){         //get attribute from element. See W3schools get getAttribute() from HTML DOM element for details.         var colorValue = fHtmlElement.getAttribute("valuecolor");         //safegaurd. The user can click on something else then the lights.         if(colorValue){            //directly change the color variable by feeding the color value from the element to the colorSwitch object            //which returns the next color            trafficLightData.color = trafficLight.colorSwitch[trafficLightData.color];            //update from template            trafficLight.update(trafficLightData);         }    }, this); }, this); trafficLight.show();

Et voila. As the data object holds the actual value that can be used to identify the current state of the Component and the Component shows the correct state.

Optional improvements
To make this component more useful it needs a couple of things.

Use a Component or Panel as you base instead of Window, it’s more easily usable inside layouts. You might even want to consider using Ext.form.Field as a base is even lighter.

Give it fixed height and width, else you need to redesign the layout to scale.

You can also make it dynamic by being able to add any colors by a config option.

Expose something like an setValue and GetValue so you don’t have to fiddle with the data object and Update(). You might also want to expose an onValueChange() or similar event.

You can use background-color or border color to make the selection more visible and use a pointer on the values to make it appear clickable.
Note: CSS code with Internet Explorer ‘hack’

Final thoughts
Making a component like this is (arguably) easy. This is one of the things that make ExtJs stand out as it gives you tools, but also the possibility to easily extend on those tools to suit them for your needs. To actually create a new component you might want to look at our tutorials we have about extending and creating new components.

The possibilities of XTemplate are not exhausted by a long shot, see my article about advanced XTemplating to get a grip on those. But in the mean time, I hope you have been able to follow up on my rambling and have a grasp on the basic concept of the XTemplate.

Have a nice day.

ExtJs 3.4 – Using XTemplate – Advanced

This article goes more in dept on XTemplate usage, for an outline, look at “Using XTemplate – Basics”.

Feeding an object to XTemplate
Quick refresh. Anything within the root of given data object can be called in the template using {propertyName}.

var tpl = new Ext.XTemplate(

Name: {name}

', '

Full name: {nameObject.first} {nameObject.last}

' ); var dataObj = { name: 'demo text', nameObject: { first: 'thirst', last: 'past' }; tpl.overwrite(panel.body, data);

Simply using name.firstname could be using to reach deeper elements when objects are nested.

If statement
In the simple example we already showed you how to use the if statement.

var tpl = new Ext.XTemplate(

Name: {name} good

' ); var dataObj = {    name: 'demo text' }; tpl.overwrite(panel.body, data);

The if statement also supports lower then < and higher then > as well as the <= and >= variations.
Although these expressions work on string, we do not recommend using them like that because it provide tricky behavior one might only understand when you know how character encoding works.

Feeding an array of objects to XTemplate
Then more interesting things. You can loop through arrays and template objects inside them.
For example:

var tpl = new Ext.XTemplate(

Name: {name} good

', '', 'Name: {name}
', 'Age: {age}
', '
' ); var dataObj = {    name: 'demo text',    kids: [         { name: "sammie", age: 10 },         { name: "tom", age: 13 },    ] }; tpl.overwrite(panel.body, data);

Both kids will be shown with their ages. When looping an array of strings use . to point to the base of the iterated element.

Using self defined functions inside the template
Closing the parameter list of a template with an object abless you to set things to the template object, but can also be used to add self defined functions.

var tpl = new Ext.XTemplate(

Name: {name} good

', '', 'Name: {name}
', 'Age: {age}
', 'Baby: ', 'Yes', 'No', '
',     {         //xtemplate properties         compiled: true,         disableFormats: true,         //custom function         isBoy: function(name){             return name == 'Timmy';         },         isBaby: function(age){             return age < 1;         }     } ); var dataObj = {    name: 'demo text',    kids: [         { name: "sammie", age: 10 },         { name: "tom", age: 13 },         { name: "lillie", age: 0 },    ] }; tpl.overwrite(panel.body, data);

As you can see above a function is used along with the for function, to loop through the children and see if they are babies.

Basic math functions
When dealing with integers + – / and * can be used to directly alter the value before showing them inside the template.
So something like:

var tpl = new Ext.XTemplate(

Birth year: {current_year - age}


Is permitted and could be useful for example to show a certain value from 3 different offsets.

Xtemplate is a excellent way to do layout as it makes markup readable using powerful tools to make dynamic markup functional. Also because it’s almost pure code when compiled it delivers high performance also reducing memory when reused on many elements.

And that’s all I have to say about that.

ExtJs 3.4 – Tips and tricks


This post is mostly a whole bunch of information I have gathered to using ExtJs 3.4 grouped by different subjects.

I hope any one stuck with Extjs 3.4 to have use for it.

Errors and possible solutions

Writing code and debugging ExtJs can sometimes be a pain because errors trown by browsers are not always clear. Like with most software, not all errors shown point directly to the actual problem. Unforntunately because javascript is very flexible, it can go wrong on many levels.

The following list gives you a guide in which errors indicate to which problems.

this.addEvents is not a function:’statesave’
Check if you use new for all of your created Ext components.

‘events’ is null or not an object
Check comma’s in items arrays

‘minWidth’ is null or not an object
Check comma’s in buttons arrays.

Expected identifier, string or number
Check comma’s inside Ext element config objects or/and arrays.

Comp is undefined
Check for non existing or empty references in an items list.

‘id’ is null or not an object
Check comma’s in ColumnModel arrays.

Unterminated string constant
If it occurs in Internet Explorer it is likely caused by disabling a form prior uploading a file. This somehow causes internet explorer to not send any form information when it is submitted.

TypeError: this.ds is undefined
Stores is not defined for a grid(panel)

Unable to get value of the property ‘0’: object is null or undefined
Check comma’s in field array of stores.

TypeError: this.config[col] is undefinedvar width = this.config[col].width;
Column model with autoexpand not pointing to a valid column. Must point to an id that exists within the column model.

TypeError: c is undefined
Calling add() on a panel/component with an empty or otherwhise faulty reference

Debugging events

Blog about logging all events. https://coderwall.com/p/jnqupq

Ext.util.Observable.capture(myObj, function(evname) {console.log(evname, arguments);})

Store query on exact value

var selectedOptions = this.optionStore.query('id', new RegExp('^' + Ext.escapeRe(String(selRecord.get("answer"))) + '$'));
   //Returns: MixedCollection\\
   //Returns an Ext.util.MixedCollection of the matched records

Store ‘fix’ modifiedRecords()

ExtJS store by default does NOT remove records from modified records on remove or load.
To make this happen use pruneModifiedRecords: true to do this

    this.data.productsComboStore=new Ext.data.SimpleStore({
        pruneModifiedRecords: true

Create new record for store

   var data = { id: 4, name: 'something' }; //initial data
   var recCreate = myStore.recordType;      //cosntructor for a new record (can allso be called directly)
   var rec = new recCreate(data);           //create record
   rec.set("id", 0);                        //alter after creation
   myStore.add(rec);                        //add to store

Find row index from record

   var recIndex = myStore.indexOf(rec);

Find data index from columnIndex and record from rowIndex

var dataIndex = fGrid.getColumnModel().getColumnAt(fColumnIndex).dataIndex;
var record = fGrid.getStore().getAt(fRowIndex); 
var recValue = record .get(dataIndex);

Using filter with combobox

Apply following config options on combo to make it work

clearFilterOnReset: false, //to make filter on store work
lastQuery: '', //another filter fix

Grid rendereres

percentageRenderer:function(fValue, fMeta, fRecord, fRowIndex, fColumnIndex, fStore) {
        fMeta.css += "cssClass";
        return fValue + "%";
checkboxRenderer:function(fValue, fMeta, fRecord, fRowIndex, fColumnIndex, fStore){
    return '
'; }

Set scope of renderer to current object

renderer: {
    fn: this.someUsefulRenderer,
    scope: this

Grid cellclick with image or other elements in renderer

When rendering images or other deep elements within a cell the cellclick events do not longer work correctly. To fix this increase the GridViews depth search paramters. This works on any type of grid view.

view: new Ext.grid.GridView({
   cellSelectorDepth: 4, //increase to find deeper elements
   rowSelectorDepth: 10 //increase to find deeper elements

Grid using drag an drop in grids

define following grid config options

enableDragDrop: true, 
ddGroup: 'mygrid-dd',  
ddText: 'Place this row.'

Create drop target class after render

this.data.grid.period.on("afterrender", function(){
   var store = this.stores.periodEdit; //change to actual store
   var grid = this.periodGrid;  //change to actual grid
var ddrow = new Ext.dd.DropTarget(grid.getEl(), {  
     ddGroup: 'mygrid-dd',  
     copy: false,
     scope: this
}, this);

Override notifyOver on this dropTarget instance to see if may be dropped Notice: using ‘dd.getDragData(e)’ causes the selections in the selectionModel to be changed

notifyOver : function(dd, e, data){
  var sourceIndex = data.rowIndex; //get sourceIndex
  var targetIndex = dd.getDragData(e).rowIndex; //get targetIndex

Override notifyDrop on this dropTarget instance to do an action when dropped

notifyDrop : function(dd, e, data){
    var sourceIndex = data.rowIndex; //get sourceIndex
    var targetIndex = dd.getDragData(e).rowIndex; //get targetIndex

Prompt for question

When you want input from the user on a question. Questions like: “sure you want to delete this?”, “Sure you want to go on and lose your unsaved data” etc.
Use the here under described function
Note: Although the buttons can be localized the answer inside the function doesn’t change. Look up the function to see more button configurations if needed.

	title: "Opslaan",
	msg: "Would you like to delete this item?", //use translate to localize the message
	width: 400,
	buttons: Ext.Msg.YESNO,
//      buttons : { ok: 'Actie uitvoeren', cancel: 'Terug' },
	closable: false,
	hideBorders: true,
	style: "border: 0;",
	fn: function(answer, text){
		if (answer == "yes"){
		else {
			//do nothing
	icon: Ext.MessageBox.QUESTION,
	scope: this

Checkbox column in grid

Toggle selection

    this.grid.on("cellclick", function(grid, rowIndex, columnIndex) {
        //get record
        var rec = grid.store.getAt(rowIndex);
        //get data index
        var dataIndex= grid.getColumnModel().getDataIndex(columnIndex);
        //toggle value false/true
        rec.set(dataIndex, !rec.get(dataIndex));
    }, this);


	function(fValue, fMeta, fRec, fRow, fCol, fStore){
             fMeta.css += " x-grid-col-selected";
             return '
'; }

Grouping grid The column you want to group with must be included within the columnModel. Even if it’s hidden, it MUST be included.

Use CSS background class to an image


Replacing or reseting upload field

Because of security reasons an upload field cannot be set or reset.
The only way to do so, is to replace the whole field.

See the example below:

//replace upload field
var config = uploadField.initialConfig;
uploadField = new Ext.form.TextField(config);
//re-add to the fomd the upload field contained too
//this can also be a grouping label etc

Show / hide loadmask

When you are loading or saving something inside your interface, you don’t want the user to change things that might get updated the next second or will not be saved because the actual data is already send to the server. Additionally you would like show the user a vissual indication something is going on.

The following functions add a loadmask to a component to achieve this. The inner workings have been proven to fix problems that occur when this function is called before the actual component is rendered. And even shows the loadMask in the event that rendering completes before loading does.

    //show load mask
    //shows it on this gui, waits for gui to render if not already done 
    //and if hideMasks is called before showLoadMask. The loadMask will not be shown.
        //see if main screen is already rendered
            //if no loadmask created
                //create loadmask
                this.loadMask = new Ext.LoadMask(this.getEl(), {
                    msg: app.instance.translate("loading data") + "..."
            //if supress load mask flag is set
                //do now show mask
                delete this.surpressLoadMask;
                //if everything ok, show load mask
            //if main screen not rendered, rerun when rendered with small delay
            this.on('render', this.showLoadMask, this, {single: true, delay: 100});
    //hide the load mask (and additional masks if added)
        //if loadmask is created
            //hide loadmask
            //if loadmask is not created, but this function is called. 
            //set supressloadmask flag to prevent load mask from being shown here after
            this.surpressLoadMask = true;