Some ExtJS patterns I enjoy

It’s always nice to stumble upon patterns that make code both functional and beautiful at the same time. Among those, of late I have been abusing these patterns when developing ExtJS components.

For example, a pattern from ExtJS itself uses Ext.applyIf to both ensure an object literal exists and then to apply default values unless they’re already defined. Such a pattern can find widespread use in any project.

this.simpleConfig = Ext.applyIf(this.simpleConfig||{}, {
  width:500,
  height:250
});

Another I rather enjoy I first noticed in an Ext Direct implementation for Rails. The functions being applied are defined after the plugin on a function prototype specifically for that purpose. It’s nice and clean.

liaison.klass.plugin.OnData = Ext.extend(Object, {
	constructor:function(config) {
		Ext.apply(this, config);
	},
 
	init:function(p) {
		Ext.applyIf(p, liaison.klass.plugin.OnData.Methods.prototype);
		p.addEvents('data', 'update-data', 'create-data', 'delete-data');
		p.on('data', p.onData, p);
	}
});
 
liaison.klass.plugin.OnData.Methods = function() {};
liaison.klass.plugin.OnData.Methods.prototype = {
 
	onData:function(action, result) {
		this.fireEvent(action+"-data", this[action+"Record"](result));
	}
};

Another pattern from ExtJS itself I hadn’t thought to mention, above, is concisely defining and calling functions based on some string. For example, I avoid the need for a case statement or an if block when deciding amongst functions prefixed with the string action. Instead, onData is a compound one liner that fires an event based on the results of a conditionally named function. Fun!

Finally, I noticed a short pattern for managing namespaces in a plugin by ExtJS forum member stephen.friedrich. I employ it when building up my various FormPanel classes.

(function() {
  var ns = Ext.ns('liaison.view.form.membership');
  ns.NewPanel = Ext.extend(liaison.components.form.DefaultFormPanel, {
  ...
  });
  Ext.reg('membership-new-form', ns.NewPanel);
)();

Simple, but effective. It’s nice to collect private field configuration items in local variables.

What patterns do you enjoy using?

3 Comments

  1. Posted 12/27/2009 at 7:00 pm | Permalink

    Interesting

  2. Posted 12/28/2009 at 5:38 pm | Permalink

    I like the last pattern in particular, it’s especially useful in ensuring small compiled code size.

    For the applyIf pattern I tend to split that into calls:

    this.someObject = this.someObject || {};
    Ext.applyIf(this.someObject, {…});

    it’s slightly longer overall, but easier to understand quickly what’s going on.

    Nice work.

  3. Posted 12/28/2009 at 10:01 pm | Permalink

    Makes sense. I’m a sucker for conciseness, though. I cram as much as I typically can in a single line. I’ve become a serial abuser of ? : syntax as well.

Post a Comment

Your email is never shared. Required fields are marked *

*
*