Aaron Conran of ExtJS just published a post today recommending using namespaces to organize your Javascript code. I have a rewrite of the Ext.namespace function that I find a little more useful.
I wanted to do 2 things. Firstly I wanted to be able to do this: (it saved typing)
1 2 3 4 5 6 7 8 9 10 |
(function(){ var NS = Ext.namespace("com.succinctllc.home.panel"); NS.MyTestPanel = function(cfg){ NS.MyTestPanel.superclass.constructor.call ... etc }; Ext.extend(NS.MyTestPanel, Ext.Panel, { ...etc... }); })() |
So, as you can see, I save a lot of typing when calling superclass methods. By returning the namespace from my custom Ext.namespace function (source at the bottom of this post) I am able to do this.
I also wanted to be able to apply “namespaces” to custom objects. For example, if I needed to build out a simple javascript object ensuring that a path of properties exist like so:
1 2 3 |
var myObject = {}; Ext.namespace(myObject, "user.firstName", "user.lastName"); myObject.user.firstName = "Jason"; |
The above code is a trivial example. I really use it to construct objects that are parseable by a JsonReader given the JsonReader’s configuration. I won’t get into why I do this… but I will just say it involves on-demand store loading from a tree datasource based on tree node expansions.
Please consider this code as a replacement for the default Ext implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Ext.namespace = function(namespacePath){ var i = 1, a=arguments, ptr = null, l1, l2, pathArr, j = 0, base=namespacePath; if (typeof base != "object") { i = 0; base = window; } for(l1=a.length; i<l1; i++){ pathArr = a[i].split("."); ptr = base; for(l2=pathArr.length; j<l2; j++){ if (typeof ptr[pathArr[j]] == 'undefined') ptr[pathArr[j]] = {}; ptr = ptr[pathArr[j]]; } } return ptr; }; |