< Developing the web />

Decoupling fonts from code in ExtJs

In this post I’m showing you a specific example of how to use a function to set the glyphs in ExtJs buttons, but it covers topics that can be ported to similar problems. These are:

Our base code is the following, having an application with one view and two buttons. Each button has a glyph assigned to it.

Ext.application({
    requires: [
		'Ext.container.Viewport'
	],
	name: 'ExampleApp',
	appFolder: 'app',

	controller: [
		'myController'
	],

	launch: function () {
		var me = this;
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [{
                xtype: 'myView',
                id:    'myAwesomeView',
                app:    me
            }]
        });
	}
});

Ext.define('ExampleApp.view.MyView', {
	extend: 'Ext.panel.Panel',
	alias: 'widget.myView',

	width: 200,
	height: 100,

	initComponent: function () {
		this.docketItems = [{
			xtype: 'toolbar',
			defaultType: 'button',
			items: [{
				name: 'refreshButton',
				glyph: 79
			}, {
				name: 'addUserButton',
				glyph: 103
			}]
		}];

		this.html = 'Hello, I\'m a panel';
	}
});

Clarifying and decoupling

In the following code, the number of the glyph is changed for a function that returns a number for a given key. Since there is no documentation of the glyphs in ExtJs 4, you have to render every posible glyph and then take note of every useful one or remember it every time you want to use it. Using a key to map a number makes it easier for people to remember a given glyph.

The second and most important reason is that this creates an interface between glyphs/fonts and code. If in the future you decide to change your font for any reason (you found another one with more glyphs or they’re more beautiful), you would need to change the code on every button and component you used your old font. So preventing that this become a pain in the future, you can use this interface and when you change your font, change your interface once and all your app will be affected (like you do in css);

Ext.define('ExampleApp.view.MyView', {
    extend: 'Ext.panel.Panel',
	alias: 'widget.myView',

	width: 200,
	height: 100,

	initComponent: function () {
		Ext.setGlyphFontFamily('MyFont');

		this.docketItems = [{
			xtype: 'toolbar',
			defaultType: 'button',
			items: [{
				name: 'refreshButton',
				glyph: myLib.getGlyph('refresh') 	// Call the lib for a refresh glyph number
			}, {
				name: 'addUserButton',
				glyph: myLib.getGlyph('addUser') 	// Keys are easier to remember than numbers
			}]
		}];

		this.html = 'Hello, I\'m a panel';
	}
});

/**
 * This function will do the interface between font and code
 */
var myLib = (function () {
	return {
		getGlyph: function (name) {
			switch (name) {
				case 'refresh':
					return 79;
				break;

				case 'addUser':
					return 103;
				break;

				default:
					return 32;	// Blank space
			}
		}
	}
})();

Dictionaries in Javascript

The past code uses a switch-case to determine which glyph number to return. If the number of keys grow fast, your code will become slower and bigger. Then you can change it to a dictionary-like structure so it performs better and cleaner. The following is how your code should be at the end.

  • #Javascript
  • #Code Patterns
  • #ExtJs
  • 8th Aug 2013 / 1 note

    Creating multiple and dynamic callbacks for a single event

    Javascript is an event driven language, and it is very powerful at this. This time I’m going to show you how to manage multiple and dynamic callbacks for a single event.

    While working on a web app, I encountered the need of having to add a new callback for an event that already had a callback. I’m working with ExtJs 4, so I had one event listening when data is loaded from server and ready for a store. But if another module is active, I needed to perform extra code for the given event. A first my options where:

    So while trying to code the second one I came with the idea of having a single callback that could call different functions depending of the state of the application, and without the need of the code to be hardcoded.

    The callback manager is pretty simple and goes like this:

    And here is an example of how you would use it. In this case I’m using ExtJs 4, with a controller and a store. The event we want to catch is when the store loads. One function [countStoreRecords()] is always called, and the other function [showRecordsOnGrid()] is called only if a window exists.

  • #Javascript
  • #ExtJs4
  • #Callback
  • #Events
  • 28th Jul 2013

    How to set custom text to MessageBox buttons in ExtJs 4?

    Today I was working with MessageBoxes in ExtJs 4 and I stumble upon with the trouble of language. The button’s text is obviously in english, but what if you’re developing for hispanic audiences or you just want to set custom text to this buttons? When I tried to change the text I had a hard time finding out how to achieve this. 

    /**
     * Eg. MessageBox with three default buttons.
     */
    Ext.Msg.show({
        title:'Caution',
        msg: 'Display your message here!',
        buttons: Ext.Msg.YESNOCANCEL,        // Displays a Yes, No and Cancel buttons
        fn: myCallbackFunction,
        animEl: 'elId'
    });
    

    (MessageBox configuration with default buttons)

    Although there are a few sites and forums with instructions on how to do it

    any of these worked for me with version 4.2.

    It was until I tried with a  configuration from version 1.1.1 that I achieved the result. Here is the code:

    /**
     * Eg. How to display a MessageBox with custom
     * text in the buttons.
     */
    Ext.Msg.show({
        title:'Caution',
        msg: 'Display your message here!',
        buttonText: {                        // Set the custom text here
            ok: 'Custom Ok text',
            yes: 'Custom Yes text',
            no: 'Custom No text'
        },
        fn: myCallbackFunction,
        animEl: 'elId'
    });
    

    Edit code on JsFiddle

  • #Javascript
  • #ExtJs
  • #ExtJs4
  • #Sencha
  • 11th Jul 2013

    Why NaN isn’t equals to itself?

    In Javascript, NaN object is a curious case. One of its properties is that it isn’t equals to itself:

    NaN === NaN;    // false
    

    Many consider this an error of the language, but after reading some articles, comments and discussions over the Internet, I figured out a logic conclusion.

    Operations like the following produce NaN, but that doesn’t imply that they are equal to each other:

    log (-1) === NaN;     // true
    100/0 === NaN;        // true
    log (-1) === 100/0;   // false
    

    NaN being equals to itself would also imply that:

    NaN/NaN === 1;      // false
    NaN - NaN === 0;    // false
    

    Anyway, we can use the isNaN() function to test a variable. As shown in Mozilla Developer Network:

    NaN === NaN;          // false
    Number.NaN === NaN;   // false
    isNaN(NaN);           // true
    isNaN(Number.NaN);    // true
    

    Further reading at IEEE 754 Standard.

  • #javascript
  • #NaN
  • 7th Jul 2013

    Measuring execution times in Javascript

    I’m sharing with you an easy way I learned to measure execution time of certain pieces of code in Javascript. The only thing you have to do is create two Date objects, on before the piece of code and the other after so you can compare them. In the following code I create two arrays in different ways as an example to compare which one is faster:

    Consider running your test several times because the execution times may vary each time. Then you can take the average running times and decide for the best option.

  • #Javascript
  • #Debugging
  • 3rd Jul 2013