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
Interesting
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.
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.