Ext中的Module模式

在Ext中大量应用了Module pattern,对于新手而言可能会有些不解,关于Module模式可以参见这个链接: www.iteye.com/topic/93650(javaeye翻译)
,英文版 yuiblog.com/blog/2007/06/12/module-pattern/
具体而言,一个Module如下:
  1. module = function(){
  2. var count = 0; // Private Variable for the module. Not accessible from outside
  3. var increaseCount = function(){ // Private function. Not accessible from outside
  4. count++;
  5. };
  6. return {
  7. init : function(){ // Priviledged method. Can be called from outside
  8. // Here comes the initialisation code
  9. },
  10. getCount : function(){ // Priviledged method. Can be called from outside
  11. return count;
  12. },
  13. checkCount : function(){
  14. increaseCount();
  15. if (this.getCount() > 10)
  16. alert("count is greater than 10");
  17. }
  18. }
  19. }();
在这种情况下,你只能访问return 部分的代码,其他的代码对于外界都是不可见的。一个典型的访问方法是:
  1. module.getCount();
其他的变量,如count,increaseCount,都是私有的,不能直接从外部访问。
在Ext中,最常见的一个代码格式就是:

  1. module = function(){
  2. var count = 0; // Private Variable for the module. Not accessible from outside
  3. var increaseCount = function(){ // Private function. Not accessible from outside
  4. count++;
  5. }
  6. return {
  7. init : function(){ // Priviledged method. Can be called from outside
  8. // Here comes the initialisation code
  9. },
  10. getCount : function(){ // Priviledged method. Can be called from outside
  11. return count;
  12. },
  13. checkCount : function(){
  14. increaseCount();
  15. if (this.getCount() > 10)
  16. alert("count is greater than 10");
  17. }
  18. }
  19. }();
  20. Ext.onReady(module.init, module);

In the last statement we are doing many things, it executes the module.init method when the document has been completely loaded and sets its scope to module. Setting the scope to module means you can call the checkCount method from inside init method like this.

你可能感兴趣的:(ext,Blog)