ExtJS4.0源代码分析----类系统之类的创建

ExtJS4.0的类系统是整个框架的基础且核心的架构设施,其它所有的功能扩展都是建立在类系统上的。在ExtJS4.0中,类系统相对以前的版本有大幅度的改变,在以前的版本中,定义一个新类是在一个已经存在的类如Object的基础上调用

Java代码   收藏代码
  1. var myClass = Ext.extend(Object, { ... });  
进行扩展而来,这样我们不能方便的给新建的类添加statics属性或方法及mixins等功能,且新建的类需要依赖Object等这些要继承的类,Object也会递归的依赖它的父类,如果这些类未创建就会出现错误,所以在以前的版本中干脆把整个ext-all.js在一开始就全部加载进来并创建整个框架中定义的所有类,这样即使你在一个应用中只使用ExtJS的一个类也要把整个ExtJS的类加载进来,大大将低了程序运行效率。在extjs4.0中通过使用
Java代码   收藏代码
  1. Ext.define(className, members, onClassCreated);  
来创建类解决了上面的问题。其中className是创建的类的名字,是String类型的;members是给要创建的类添加的配置信息,主要包括requires(要求使用的类),extend(要继承的类),mixins(向创建的类中要掺进其它类的信息),config(给创建的类配置属性方法等),statics(给类增加静态属性或方法),以及其它的一些属性方法等信息,这些配置信息在后面会详细说明;onClassCreated是类创建后的回调函数。 

在ExtJS4.0中,与类创建相关的js文件主要有src/core/src/class中的Base.js,Class.js,ClassManager.js,Loader.js。其中Base.js定义了Base类,Base类是ExtJS4.0中所有通过Ext.define定义的类的直接或间接父类,Base类中定义了一些通用的实例与静态属性与方法;Class.js文件中定义了Class类,所有通过Ext.define定义的类都是Class的实例(其实是Class构造函数中的newClass类);ClassManager.js文件中定义了ClassManager单例,它主要负责对类的管理,如类的创建与类实例化等;Loader文件中定义了Loader单例,实现了ExtJS4.0中动态加载类的功能。 

以ExtJS中的Component类为例,它的类创建代码如下:
Java代码   收藏代码
  1. Ext.define('Ext.Component', {  
  2.   
  3.     /* Begin Definitions */  
  4.   
  5.     alias: ['widget.component''widget.box'],  
  6.   
  7.     extend: 'Ext.AbstractComponent',  
  8.   
  9.     requires: [  
  10.         'Ext.util.DelayedTask'  
  11.     ],  
  12.   
  13.     uses: [  
  14.         'Ext.Layer',  
  15.         'Ext.resizer.Resizer',  
  16.         'Ext.util.ComponentDragger'  
  17.     ],  
  18.   
  19.     mixins: {  
  20.         floating: 'Ext.util.Floating'  
  21.     },  
  22.   
  23.     statics: {  
  24.         // Collapse/expand directions  
  25.         DIRECTION_TOP: 'top',  
  26.         DIRECTION_RIGHT: 'right',  
  27.         DIRECTION_BOTTOM: 'bottom',  
  28.         DIRECTION_LEFT: 'left',  
  29.   
  30.         VERTICAL_DIRECTION: /^(?:top|bottom)$/  
  31.     },  
  32.   
  33.     resizeHandles: 'all'  
  34.   }  
  35. );  

一个类创建前与创建后分别会有前置处理器与后置处理器对类进行装饰以增强类的功能,下面一张图片对类的创建过程作了一个详细的说明:  
类创建前会有loader,extend,mixins,config,statics对类增加配置信息,且这些preprocessor是按顺序进行的,postprscessor主要包括alias(为类设置别名)与legacy等。 

Ext.define实际上是ClassManager中的create方法的别名,ClassManager是一个单例,里面主要定义了与类的创建(create)与实例化类(instantiate)相关的方法。所以
Java代码   收藏代码
  1. Ext.define(className, data, onClassCreated);  
实际上是调用了
Java代码   收藏代码
  1. ClassManager.create(className, data, onClassCreated);  
。在此方法内部,会先将className添加到data,之后会new一个Class并返回,所以可以说Ext.define出的类都是Class这个类的实例(其实new Class后返回的是其内部的newClass类),下面是裁剪后的代码:
Java代码   收藏代码
  1. create: function(className, data, createdFn) {  
  2.             var manager = this;  
  3.   
  4.             data.$className = className;  
  5.   
  6.             return new Class(data, function() {  
  7.                 var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,  
  8.                     registeredPostprocessors = manager.postprocessors,  
  9.                     index = 0,  
  10.                     postprocessors = [],  
  11.                     postprocessor, postprocessors, process, i, ln;  
  12.   
  13.                 delete data.postprocessors;  
  14.   
  15.                 for (i = 0, ln = postprocessorStack.length; i < ln; i++) {  
  16.                     postprocessor = postprocessorStack[i];  
  17.   
  18.                     if (typeof postprocessor === 'string') {  
  19.                         postprocessor = registeredPostprocessors[postprocessor];  
  20.   
  21.                         if (!postprocessor.always) {  
  22.                             if (data[postprocessor.name] !== undefined) {  
  23.                                 postprocessors.push(postprocessor.fn);  
  24.                             }  
  25.                         }  
  26.                         else {  
  27.                             postprocessors.push(postprocessor.fn);  
  28.                         }  
  29.                     }  
  30.                     else {  
  31.                         postprocessors.push(postprocessor);  
  32.                     }  
  33.                 }  
  34.   
  35.                 process = function(clsName, cls, clsData) {  
  36.                     postprocessor = postprocessors[index++];  
  37.   
  38.                     if (!postprocessor) {  
  39.                         manager.set(className, cls);  
  40.   
  41.                         Ext.Loader.historyPush(className);  
  42.   
  43.                         if (createdFn) {  
  44.                             createdFn.call(cls, cls);  
  45.                         }  
  46.   
  47.                         return;  
  48.                     }  
  49.   
  50.                     if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {  
  51.                         process.apply(this, arguments);  
  52.                     }  
  53.                 };  
  54.   
  55.                 process.call(manager, className, this, data);  
  56.             });  
  57.         },  

下面是Class的核心代码: 
Java代码   收藏代码
  1. Ext.Class = Class = function(newClass, classData, onClassCreated) {  
  2.         if (typeof newClass !== 'function') {  
  3.             onClassCreated = classData;  
  4.             classData = newClass;  
  5.             newClass = function() {  
  6.                 return this.constructor.apply(this, arguments);  
  7.             };//这才是最终创建的类  
  8.         }  
  9.   
  10.         if (!classData) {  
  11.             classData = {};  
  12.         }  
  13. //创建类时可以自定义preprocessors,否则使用默认的preprocessors。  
  14. //默认preprocessors有  
  15. //['extend', 'statics', 'inheritableStatics', 'mixins', 'config']  
  16.         var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),  
  17. //获取已经注册的preprocessors  
  18.             registeredPreprocessors = Class.getPreprocessors(),  
  19.             index = 0,  
  20.             preprocessors = [],  
  21.             preprocessor, preprocessors, staticPropertyName, process, i, j, ln;  
  22.   
  23. //继承Base类的静态方法,在ExtJS4.0中,通过Ext.define创建的类都是Base的直接  
  24. //或间接子类,后面在分析extend前置处理器时会详细说明,此处只把Base中的static  
  25. //属性掺进newClass中。  
  26.         for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {  
  27.             staticPropertyName = baseStaticProperties[i];  
  28.             newClass[staticPropertyName] = Base[staticPropertyName];  
  29.         }  
  30.   
  31.         delete classData.preprocessors;  
  32. //获取总是要注册的preprocessor(如extend)及创建的类注册的preprocessor  
  33.         for (j = 0, ln = preprocessorStack.length; j < ln; j++) {  
  34.             preprocessor = preprocessorStack[j];  
  35.   
  36.             if (typeof preprocessor === 'string') {  
  37.                 preprocessor = registeredPreprocessors[preprocessor];  
  38.   
  39.                 if (!preprocessor.always) {  
  40. //创建类指定了要注册的preprocessor  
  41.                     if (classData.hasOwnProperty(preprocessor.name)) {  
  42.                         preprocessors.push(preprocessor.fn);  
  43.                     }  
  44.                 }  
  45.                 else {  
  46. //总是要注册的preprocessor  
  47.                     preprocessors.push(preprocessor.fn);  
  48.                 }  
  49.             }  
  50.             else {  
  51.                 preprocessors.push(preprocessor);  
  52.             }  
  53.         }  
  54. //类创建后的回调函数  
  55.         classData.onClassCreated = onClassCreated;  
  56. //preprocessor对类作增强后,类创建前的回调函数,  
  57. //即将data中指定的配置信息掺进newClass的prototype中  
  58.         classData.onBeforeClassCreated = function(cls, data) {  
  59.             onClassCreated = data.onClassCreated;  
  60.   
  61.             delete data.onBeforeClassCreated;  
  62.             delete data.onClassCreated;  
  63. //将data中指定的配置信息掺进newClass的prototype中  
  64.             cls.implement(data);  
  65. //调用类创建后的回调函数,主要是通过postpreprocessor对 newClass增强  
  66.             if (onClassCreated) {  
  67.                 onClassCreated.call(cls, cls);  
  68.             }  
  69.         };  
  70. //preprocessor  
  71.         process = function(cls, data) {  
  72.             preprocessor = preprocessors[index++];  
  73. //所有preprocessor调用结束后调用onBeforeClassCreated  
  74.             if (!preprocessor) {  
  75.                 data.onBeforeClassCreated.apply(this, arguments);  
  76.                 return;  
  77.             }  
  78. //调用preprocessor直到所有preprocessor处理结束  
  79.             if (preprocessor.call(this, cls, data, process) !== false) {  
  80.                 process.apply(this, arguments);  
  81.             }  
  82.         };  
  83.   
  84.         process.call(Class, newClass, classData);  
  85.   
  86.         return newClass;  
  87.     };  

ExtJS4.0会首先加载Base,Class,ClassManager,Loader及其所依赖的类及其它一些工具类或方法,也就是ext-debug.js或ext.js中的代码,其中注册前置处理器的代码是在Class中定义的,代码如下:
Java代码   收藏代码
  1. registerPreprocessor: function(name, fn, always) {  
  2.             this.preprocessors[name] = {  
  3.                 name: name,//前置处理器的名字  
  4.                 always: always ||  false,//是否总是要注册  
  5.                 fn: fn //当前前置处理器的回调函数  
  6.             };  
  7.   
  8.             return this;  
  9.         }  

在Class中注册的preprocessor有['extend', 'statics', 'inheritableStatics', 'mixins', 'config'],同时默认的前置处理器也是这几个。在Class中也定义了一个叫做setDefaultPreprocessorPosition的方法,其作用是将preprocessor插入到默认preprocessors的指定位置,而这个要插入的preprocessor必须是已经注册的(即通过registerPreprocessor方法注册到Class中的preprocessors),其定义如下: 
Java代码   收藏代码
  1. setDefaultPreprocessorPosition: function(name, offset, relativeName) {  
  2.             var defaultPreprocessors = this.defaultPreprocessors,  
  3.                 index;  
  4.   
  5.             if (typeof offset === 'string') {  
  6.                 if (offset === 'first') {  
  7.                     defaultPreprocessors.unshift(name);  
  8.   
  9.                     return this;  
  10.                 }  
  11.                 else if (offset === 'last') {  
  12.                     defaultPreprocessors.push(name);  
  13.   
  14.                     return this;  
  15.                 }  
  16.   
  17.                 offset = (offset === 'after') ? 1 : -1;  
  18.             }  
  19.   
  20.             index = Ext.Array.indexOf(defaultPreprocessors, relativeName);  
  21.   
  22.             if (index !== -1) {  
  23.                 Ext.Array.splice(defaultPreprocessors, Math.max(0, index + offset), 0, name);  
  24.             }  
  25.   
  26.             return this;  
  27.         }  

其中offset取值可以是‘first’,‘last’(表示插入到队头还是队尾),‘before’,‘after’(相对relativeName插入在其前或其后)。 


在ClassManager中给要创建的类注册了className前置处理器,主要作用是从data中获取$className给要创建的类添加$className属性,方便以后的调试及获取类的信息: 
Java代码   收藏代码
  1. Class.registerPreprocessor('className', function(cls, data) {  
  2.         if (data.$className) {  
  3.             cls.$className = data.$className;  
  4.             //<debug>  
  5.             cls.displayName = cls.$className;  
  6.             //</debug>  
  7.         }  
  8.     }, true);  

并通过
Java代码   收藏代码
  1. Class.setDefaultPreprocessorPosition('className''first');  
将其变为第一个preprocessor。 


在Loader中给要创建的类注册了loader前置处理器,其主要作用是确保data中的extend,requires及mixins配置所指定的类已经加载,如果这些类还没加载则通过异步或同步的方式加载这些类,loader前置处理器会根据dependencyProperties(其值为['extend', 'mixins', 'requires'])中指定的preprocessor的顺序将data中对应的preprocessor要求使用的类名转换成实际的类,如会将
Java代码   收藏代码
  1. {  
  2.               extend: 'Ext.MyClass',  
  3.               requires: ['Ext.some.OtherClass'],  
  4.               mixins: {  
  5.                   observable: 'Ext.util.Observable';  
  6.               }  
  7.         }  
转换成
Java代码   收藏代码
  1. {  
  2.               extend: Ext.MyClass,  
  3.               requires: [Ext.some.OtherClass],  
  4.               mixins: {  
  5.                   observable: Ext.util.Observable;  
  6.               }  
  7.         }  
loader前置处理器的代码如下: 
Java代码   收藏代码
  1. Class.registerPreprocessor('loader', function(cls, data, continueFn) {  
  2.         var me = this,  
  3.             dependencies = [],  
  4.             className = Manager.getName(cls),  
  5.             i, j, ln, subLn, value, propertyName, propertyValue;  
  6.   
  7.         /* 
  8.         Basically loop through the dependencyProperties, look for string class names and push 
  9.         them into a stack, regardless of whether the property's value is a string, array or object. For example: 
  10.         { 
  11.               extend: 'Ext.MyClass', 
  12.               requires: ['Ext.some.OtherClass'], 
  13.               mixins: { 
  14.                   observable: 'Ext.util.Observable'; 
  15.               } 
  16.         } 
  17.         which will later be transformed into: 
  18.         { 
  19.               extend: Ext.MyClass, 
  20.               requires: [Ext.some.OtherClass], 
  21.               mixins: { 
  22.                   observable: Ext.util.Observable; 
  23.               } 
  24.         } 
  25.         */  
  26.   
  27.         for (i = 0, ln = dependencyProperties.length; i < ln; i++) {  
  28.             propertyName = dependencyProperties[i];  
  29.   
  30.             if (data.hasOwnProperty(propertyName)) {  
  31.                 propertyValue = data[propertyName];  
  32.   
  33.                 if (typeof propertyValue === 'string') {  
  34.                     dependencies.push(propertyValue);  
  35.                 }  
  36.                 else if (propertyValue instanceof Array) {  
  37.                     for (j = 0, subLn = propertyValue.length; j < subLn; j++) {  
  38.                         value = propertyValue[j];  
  39.   
  40.                         if (typeof value === 'string') {  
  41.                             dependencies.push(value);  
  42.                         }  
  43.                     }  
  44.                 }  
  45.                 else {  
  46.                     for (j in propertyValue) {  
  47.                         if (propertyValue.hasOwnProperty(j)) {  
  48.                             value = propertyValue[j];  
  49.   
  50.                             if (typeof value === 'string') {  
  51.                                 dependencies.push(value);  
  52.                             }  
  53.                         }  
  54.                     }  
  55.                 }  
  56.             }  
  57.         }  
  58.   
  59.         if (dependencies.length === 0) {  
  60. //            Loader.historyPush(className);  
  61.             return;  
  62.         }  
  63.   
  64.         //<debug error>  
  65.         var deadlockPath = [],  
  66.             requiresMap = Loader.requiresMap,  
  67.             detectDeadlock;  
  68.   
  69.         /* 
  70.         Automatically detect deadlocks before-hand, 
  71.         will throw an error with detailed path for ease of debugging. Examples of deadlock cases: 
  72.  
  73.         - A extends B, then B extends A 
  74.         - A requires B, B requires C, then C requires A 
  75.  
  76.         The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks 
  77.         no matter how deep the path is. 
  78.         */  
  79.   
  80.         if (className) {  
  81.             requiresMap[className] = dependencies;  
  82.   
  83.             detectDeadlock = function(cls) {  
  84.                 deadlockPath.push(cls);  
  85.   
  86.                 if (requiresMap[cls]) {  
  87.                     if (Ext.Array.contains(requiresMap[cls], className)) {  
  88.                         Ext.Error.raise({  
  89.                             sourceClass: "Ext.Loader",  
  90.                             msg: "Deadlock detected while loading dependencies! '" + className + "' and '" +  
  91.                                 deadlockPath[1] + "' " + "mutually require each other. Path: " +  
  92.                                 deadlockPath.join(' -> ') + " -> " + deadlockPath[0]  
  93.                         });  
  94.                     }  
  95.   
  96.                     for (i = 0, ln = requiresMap[cls].length; i < ln; i++) {  
  97.                         detectDeadlock(requiresMap[cls][i]);  
  98.                     }  
  99.                 }  
  100.             };  
  101.   
  102.             detectDeadlock(className);  
  103.         }  
  104.   
  105.         //</debug>  
  106.   
  107.         Loader.require(dependencies, function() {  
  108.             for (i = 0, ln = dependencyProperties.length; i < ln; i++) {  
  109.                 propertyName = dependencyProperties[i];  
  110.   
  111.                 if (data.hasOwnProperty(propertyName)) {  
  112.                     propertyValue = data[propertyName];  
  113.   
  114.                     if (typeof propertyValue === 'string') {  
  115.                         data[propertyName] = Manager.get(propertyValue);  
  116.                     }  
  117.                     else if (propertyValue instanceof Array) {  
  118.                         for (j = 0, subLn = propertyValue.length; j < subLn; j++) {  
  119.                             value = propertyValue[j];  
  120.   
  121.                             if (typeof value === 'string') {  
  122.                                 data[propertyName][j] = Manager.get(value);  
  123.                             }  
  124.                         }  
  125.                     }  
  126.                     else {  
  127.                         for (var k in propertyValue) {  
  128.                             if (propertyValue.hasOwnProperty(k)) {  
  129.                                 value = propertyValue[k];  
  130.   
  131.                                 if (typeof value === 'string') {  
  132.                                     data[propertyName][k] = Manager.get(value);  
  133.                                 }  
  134.                             }  
  135.                         }  
  136.                     }  
  137.                 }  
  138.             }  
  139.   
  140.             continueFn.call(me, cls, data);  
  141.         });  
  142.   
  143.         return false;  
  144.     }, true);  


经过上述一番注册,此时的前置处理器及顺序为['className','loader','extend','statics','inheritableStatics','mixins','config'], 
然后就会按照顺序调用这些preprocessor。className与loader前置处理器及其作用在前面已经分析过,经loader处理后,data中extend,requires及mixins指定的类被加载且被转换成了实际的类,之后会调用extend前置处理器,代码如下: 
Java代码   收藏代码
  1. Class.registerPreprocessor('extend', function(cls, data) {  
  2.         var extend = data.extend,  
  3. //Base类是所有通过Ext.define创建的类的直接或间接父类  
  4.             base = Ext.Base,  
  5.             basePrototype = base.prototype,  
  6.             prototype = function() {},  
  7.             parent, i, k, ln, staticName, parentStatics,  
  8.             parentPrototype, clsPrototype;  
  9.   
  10.         if (extend && extend !== Object) {  
  11.             parent = extend;  
  12.         }  
  13. //如果没有在data中指定要继承的类,则默认继承Base类  
  14.         else {  
  15.             parent = base;  
  16.         }  
  17.   
  18.         parentPrototype = parent.prototype;  
  19.   
  20.         prototype.prototype = parentPrototype;  
  21.         clsPrototype = cls.prototype = new prototype();  
  22.   
  23.         if (!('$class' in parent)) {  
  24.             for (i in basePrototype) {  
  25.                 if (!parentPrototype[i]) {  
  26.                     parentPrototype[i] = basePrototype[i];  
  27.                 }  
  28.             }  
  29.         }  
  30.   
  31.         clsPrototype.self = cls;  
  32.   
  33.         cls.superclass = clsPrototype.superclass = parentPrototype;  
  34. //删除data中的extend属性  
  35.         delete data.extend;  
  36.   
  37.         // 继承父类中可被继承的属性或方法  
  38.         parentStatics = parentPrototype.$inheritableStatics;  
  39.   
  40.         if (parentStatics) {  
  41.             for (k = 0, ln = parentStatics.length; k < ln; k++) {  
  42.                 staticName = parentStatics[k];  
  43.   
  44.                 if (!cls.hasOwnProperty(staticName)) {  
  45.                     cls[staticName] = parent[staticName];  
  46.                 }  
  47.             }  
  48.         }  
  49.   
  50.         // 继承父类中的config信息  
  51.         if (parentPrototype.config) {  
  52.             clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);  
  53.         }  
  54.         else {  
  55.             clsPrototype.config = {};  
  56.         }  
  57. //父类被继承后的回调函数  
  58.         if (clsPrototype.$onExtended) {  
  59.             clsPrototype.$onExtended.call(cls, cls, data);  
  60.         }  
  61. //为当前类注册被继承后的回调函数  
  62.         if (data.onClassExtended) {  
  63.             clsPrototype.$onExtended = data.onClassExtended;  
  64.             delete data.onClassExtended;  
  65.         }  
  66.   
  67.     }, true);  

其实裁剪一下,此继承的思想大致如下: 
Java代码   收藏代码
  1. function extend(SubClass,SupClass) {  
  2.      function F(){}  
  3.      F.prototype = SupClass.prototype;  
  4.      SubClass.prototype = new F();  
  5.      SubClass.superclass = SubClass.prototype.superclass = SupClass.prototype;  
  6.      return SubClass;  
  7. }  


statics前置处理器为类增加static属性或方法,代码如下:
Java代码   收藏代码
  1. Class.registerPreprocessor('statics', function(cls, data) {  
  2.         var statics = data.statics,  
  3.             name;  
  4.   
  5.         for (name in statics) {  
  6.             if (statics.hasOwnProperty(name)) {  
  7.                 cls[name] = statics[name];  
  8.             }  
  9.         }  
  10.   
  11.         delete data.statics;  
  12.     });  

实现比较简单,直接将data中的statics中指定的属性或方法掺进newClass中即可。 

inheritableStatics前置处理器设置可被继承的static属性,代码如下:
Java代码   收藏代码
  1. Class.registerPreprocessor('inheritableStatics', function(cls, data) {  
  2.         var statics = data.inheritableStatics,  
  3.             inheritableStatics,  
  4.             prototype = cls.prototype,  
  5.             name;  
  6.   
  7.         inheritableStatics = prototype.$inheritableStatics;  
  8.   
  9.         if (!inheritableStatics) {  
  10.             inheritableStatics = prototype.$inheritableStatics = [];  
  11.         }  
  12.   
  13.         for (name in statics) {  
  14.             if (statics.hasOwnProperty(name)) {  
  15.                 cls[name] = statics[name];  
  16.                 inheritableStatics.push(name);  
  17.             }  
  18.         }  
  19.   
  20.         delete data.inheritableStatics;  
  21.     });  


mixins前置处理器将指定类的prototype中的属性掺进当前类的prototype中,代码如下: 
Java代码   收藏代码
  1. Class.registerPreprocessor('mixins', function(cls, data) {  
  2.         cls.mixin(data.mixins);  
  3.   
  4.         delete data.mixins;  
  5.     });  


Base类中定义了mixin静态方法,此静态方法被新创建的newClass继承,所以可以直接在newClass上调用mixin将data.mixins中的类掺进来,其代码如下: 
Java代码   收藏代码
  1. mixin: flexSetter(function(name, cls) {  
  2.             var mixin = cls.prototype,  
  3.                 my = this.prototype,  
  4.                 i, fn;  
  5.   
  6.             for (i in mixin) {  
  7.                 if (mixin.hasOwnProperty(i)) {  
  8.                     if (my[i] === undefined) {  
  9.                         if (typeof mixin[i] === 'function') {  
  10.                             fn = mixin[i];  
  11.   
  12.                             if (fn.$owner === undefined) {  
  13.                                 this.ownMethod(i, fn);  
  14.                             }  
  15.                             else {  
  16.                                 my[i] = fn;  
  17.                             }  
  18.                         }  
  19.                         else {  
  20.                             my[i] = mixin[i];  
  21.                         }  
  22.                     }  
  23.                     else if (i === 'config' && my.config && mixin.config) {  
  24.                         Ext.Object.merge(my.config, mixin.config);  
  25.                     }  
  26.                 }  
  27.             }  
  28.   
  29.             if (my.mixins === undefined) {  
  30.                 my.mixins = {};  
  31.             }  
  32.   
  33.             my.mixins[name] = mixin;  
  34.         })  

其中flexSetter是Ext.Function.flexSetter中的一个工具函数,在整个ExtJS4.0框架中用到的地方很多,它接收一个需要两个参数的函数作参数,作用是返回一个函数,该函数接收两个参数,内部通过对返回函数参数调用flexSetter的形参函数将返回函数中的参数信息添加到调用对象中,说起来很拗口,代码如下: 
Java代码   收藏代码
  1. flexSetter: function(fn) {  
  2.         return function(a, b) {  
  3.             var k, i;  
  4.   
  5.             if (a === null) {  
  6.                 return this;  
  7.             }  
  8.   
  9.             if (typeof a !== 'string') {  
  10.                 for (k in a) {  
  11.                     if (a.hasOwnProperty(k)) {  
  12.                         fn.call(this, k, a[k]);  
  13.                     }  
  14.                 }  
  15.   
  16.                 if (Ext.enumerables) {  
  17.                     for (i = Ext.enumerables.length; i--;) {  
  18.                         k = Ext.enumerables[i];  
  19.                         if (a.hasOwnProperty(k)) {  
  20.                             fn.call(this, k, a[k]);  
  21.                         }  
  22.                     }  
  23.                 }  
  24.             } else {  
  25.                 fn.call(this, a, b);  
  26.             }  
  27.   
  28.             return this;  
  29.         };  
  30.     }  


最后的一个前置处理器是config,将data中的config对象中的信息添加newClass的prototype中,此前置处理器会自动为config中的每一个没有配置setter,getter,apply方法的属性添加setter,getter与apply方法,并将这些方法临时存放到data中,其中apply方法在对象调用setter方法时会被调用,代码如下: 
Java代码   收藏代码
  1. Class.registerPreprocessor('config', function(cls, data) {  
  2.         var prototype = cls.prototype;  
  3.   
  4.         Ext.Object.each(data.config, function(name) {  
  5.             var cName = name.charAt(0).toUpperCase() + name.substr(1),  
  6.                 pName = name,  
  7.                 apply = 'apply' + cName,  
  8.                 setter = 'set' + cName,  
  9.                 getter = 'get' + cName;  
  10. //添加setter方法  
  11.             if (!(apply in prototype) && !data.hasOwnProperty(apply)) {  
  12.                 data[apply] = function(val) {  
  13.                     return val;  
  14.                 };  
  15.             }  
  16.   
  17.             if (!(setter in prototype) && !data.hasOwnProperty(setter)) {  
  18.                 data[setter] = function(val) {  
  19. //调用相应的apply方法  
  20.                     var ret = this[apply].call(this, val, this[pName]);  
  21.   
  22.                     if (ret !== undefined) {  
  23.                         this[pName] = ret;  
  24.                     }  
  25.   
  26.                     return this;  
  27.                 };  
  28.             }  
  29. //添加getter方法  
  30.             if (!(getter in prototype) && !data.hasOwnProperty(getter)) {  
  31.                 data[getter] = function() {  
  32.                     return this[pName];  
  33.                 };  
  34.             }  
  35.         });  
  36. //将data中的config合并到prototype的config中,并删除之  
  37.         Ext.Object.merge(prototype.config, data.config);  
  38.         delete data.config;  
  39.     });  


所有的上述前置处理器被调用后,就会调用刚才注册的onBeforeClassCreated方法,代码如下:
Java代码   收藏代码
  1. classData.onBeforeClassCreated = function(cls, data) {  
  2.             onClassCreated = data.onClassCreated;  
  3.   
  4.             delete data.onBeforeClassCreated;  
  5.             delete data.onClassCreated;  
  6.   
  7.             cls.implement(data);  
  8.   
  9.             if (onClassCreated) {  
  10.                 onClassCreated.call(cls, cls);  
  11.             }  
  12.         };  

其中cls是被创建的newClass,其implement静态方法也是从Base继承而来,其作用是将参数对象(data)中的属性添加到调用对象(newClass)的prototype中,刚才在config前置处理器中生成并存放在data中的setter,getter及apply方法也会在此被添加到newClass的prototype中,代码如下: 
Java代码   收藏代码
  1. implement: function(members) {  
  2.             var prototype = this.prototype,  
  3.                 name, i, member, previous;  
  4.             //<debug>  
  5.             var className = Ext.getClassName(this);  
  6.             //</debug>  
  7.             for (name in members) {  
  8.                 if (members.hasOwnProperty(name)) {  
  9.                     member = members[name];  
  10.   
  11.                     if (typeof member === 'function') {  
  12.                         member.$owner = this;  
  13.                         member.$name = name;  
  14.                         //<debug>  
  15.                         if (className) {  
  16.                             member.displayName = className + '#' + name;  
  17.                         }  
  18.                         //</debug>  
  19.                     }  
  20.   
  21.                     prototype[name] = member;  
  22.                 }  
  23.             }  
  24.   
  25.             if (Ext.enumerables) {  
  26.                 var enumerables = Ext.enumerables;  
  27.   
  28.                 for (i = enumerables.length; i--;) {  
  29.                     name = enumerables[i];  
  30.   
  31.                     if (members.hasOwnProperty(name)) {  
  32.                         member = members[name];  
  33.                         member.$owner = this;  
  34.                         member.$name = name;  
  35.                         prototype[name] = member;  
  36.                     }  
  37.                 }  
  38.             }  
  39.         }  


至此整个newClass的创建已经完成,后面就是调用onClassCreated回调函数通过后置处理器对已经创建的类进行处理以方便对类的管理。 





后置处理器的注册是在ClassManager中定义的,代码如下:
Java代码   收藏代码
  1. registerPostprocessor: function(name, fn, always) {  
  2.             this.postprocessors[name] = {  
  3.                 name: name,  
  4.                 always: always ||  false,  
  5.                 fn: fn  
  6.             };  
  7.   
  8.             return this;  
  9.         }  

同时在ClassManager也定义了setDefaultPostprocessorPosition,其作用与在Class中定义的setDefaultPreprocessorPosition的作用相同,为了将指定后置处理器放到指定的位置。在ClassManger中注册的后置处理器及其顺序为:['alias', 'singleton', 'alternateClassName'],并将它们设置为默认的后置处理器,在Loader中通过setDefaultPostprocessorPosition将在其中注册的uses后置处理器放到先前注册的默认后置处理器的后面,这些后置处理器都不是必须的。其中alias给新创建类设置别名,别名的前缀若为'widget.',则为创建的类(newClass)增加xtype静态属性,这样以后创建类的实例时就可以直接使用xtype来代替实际的类名了;singleton使创建的类成为单例类,经过此后置处理器的处理后,会new一个该类的实例(即new newClass())并注册到ClassManager中,以后每次创建一个该类的实例时就会直接返回这个已经被注册到ClassManager中的实例(单例);alternateClassName可以为类设置可替代的类名,这个后置处理器主要是为了兼容4.0之前的版本库以前而定义的,由于ExtJS4.0对命名空间及类名作了较大调整,所以可以通过设置alternateClassName的方式让以前版本的类名指向的是4.0版本中新类名所指向的实际类;而uses后置处理器列出了要和Ext.define的类一同加载的类,这些类在被实例化前可能并未加载。 

alias后置处理器的定义如下: 
Java代码   收藏代码
  1. Manager.registerPostprocessor('alias', function(name, cls, data) {  
  2.         var aliases = data.alias,  
  3.             widgetPrefix = 'widget.',  
  4.             i, ln, alias;  
  5.   
  6.         if (!(aliases instanceof Array)) {  
  7.             aliases = [aliases];  
  8.         }  
  9.   
  10.         for (i = 0, ln = aliases.length; i < ln; i++) {  
  11.             alias = aliases[i];  
  12.   
  13.             //<debug error>  
  14.             if (typeof alias !== 'string') {  
  15.                 Ext.Error.raise({  
  16.                     sourceClass: "Ext",  
  17.                     sourceMethod: "define",  
  18.                     msg: "Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"  
  19.                 });  
  20.             }  
  21.             //</debug>  
  22.   
  23.             this.setAlias(cls, alias);  
  24.         }  
  25.   
  26.         // This is ugly, will change to make use of parseNamespace for alias later on  
  27.         for (i = 0, ln = aliases.length; i < ln; i++) {  
  28.             alias = aliases[i];  
  29.   
  30.             if (alias.substring(0, widgetPrefix.length) === widgetPrefix) {  
  31.                 // Only the first alias with 'widget.' prefix will be used for xtype  
  32.                 cls.xtype = cls.$xtype = alias.substring(widgetPrefix.length);  
  33.                 break;  
  34.             }  
  35.         }  
  36.     })  


singleton后置处理器的定义如下: 
Java代码   收藏代码
  1. Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {  
  2.         fn.call(this, name, new cls(), data);  
  3.         return false;  
  4.     });  

此处甚为巧妙,直接new一个cls的实例,之后后面的后置处理器(fn是调用后置处理器的函数,此处是递归调用)都会在这个对象上进一步处理,最后将这个实例注册到ClassManager中,以后要创建这个类的实例时直接返回的是这个实例,也就达到了单例的效果。 

alternateClassName后置处理器的定义如下: 
Java代码   收藏代码
  1. Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {  
  2.         var alternates = data.alternateClassName,  
  3.             i, ln, alternate;  
  4.   
  5.         if (!(alternates instanceof Array)) {  
  6.             alternates = [alternates];  
  7.         }  
  8.   
  9.         for (i = 0, ln = alternates.length; i < ln; i++) {  
  10.             alternate = alternates[i];  
  11.   
  12.             //<debug error>  
  13.             if (typeof alternate !== 'string') {  
  14.                 Ext.Error.raise({  
  15.                     sourceClass: "Ext",  
  16.                     sourceMethod: "define",  
  17.                     msg: "Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"  
  18.                 });  
  19.             }  
  20.             //</debug>  
  21.   
  22.             this.set(alternate, cls);  
  23.         }  
  24.     });  


uses后置处理器的定义如下: 
Java代码   收藏代码
  1. Manager.registerPostprocessor('uses', function(name, cls, data) {  
  2.         var uses = Ext.Array.from(data.uses),  
  3.             items = [],  
  4.             i, ln, item;  
  5.   
  6.         for (i = 0, ln = uses.length; i < ln; i++) {  
  7.             item = uses[i];  
  8.   
  9.             if (typeof item === 'string') {  
  10.                 items.push(item);  
  11.             }  
  12.         }  
  13.   
  14.         Loader.addOptionalRequires(items);  
  15.     });  


所有上述的前置与后置处理器被调用结束后,就会将新创建的类注册到ClassManager中,代码如下: 
Java代码   收藏代码
  1. set: function(name, value) {  
  2.             var targetName = this.getName(value);  
  3.   
  4.             this.classes[name] = this.setNamespace(name, value);  
  5.   
  6.             if (targetName && targetName !== name) {  
  7.                 this.maps.alternateToName[name] = targetName;  
  8.             }  
  9.   
  10.             return this;  
  11.         }  



至此,整个类的创建便完成了。


转载地址:http://liupengtao.iteye.com/blog/1188060

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值