2011-11-18 92 views
1

通常情况下,ExtJS组件/对象是通过将配置对象传递给它的构造函数来构造的。JavaScript对象构造

this.serviceFiltersPanel = new Ext.FormPanel({ 
     title: 'some title', 
     layout:'anchor', 
     buttonAlign: 'left', 
     buttons: [ 
      { 
       xtype: 'button', 
       text: 'Click Me', 
       handler: function() { 

        // How do I get a reference to the FormPanel 
        // under construction here? 
       }); 
      } 
     ] 
    }); 

有没有什么办法让从按钮处理程序内正在兴建的FormPanel对象的引用?

回答

2
var formPanel = new Ext.FormPanel({ 
    title: 'some title', 
    layout:'anchor', 
    buttonAlign: 'left', 
    buttons: [ 
     { 
      xtype: 'button', 
      text: 'Click Me', 
      handler: function() { 

       // Q: How do I get a reference to the FormPanel 
       // under construction here? 

       // A: use the formPanel variable. 
      }); 
     } 
    ] 
}); 

this.serviceFiltersPanel = formPanel; 
+0

我假设'formPanel'只在构造函数完成执行后才被赋值。你能解释为什么需要将FormPanel分配给两个变量?换句话说,为什么我不能像问题那样将它分配给'serviceFiltersPanel',然后在处理程序中引用该变量? –

+0

@Don,它仅在那里可用,因为它是一个全局变量。而且你是正确的,但处理程序无论如何都是在构造之后调用的,并且变量存在于全局中,因此它可以读取它。 – Esailija

+0

@Don,构造函数在按钮处理程序运行之前完成执行方式。您只需将(未执行)按钮处理程序传递给构造函数。至于为什么我将它保存在一个单独的变量中,这是因为在处理程序内'this'将引用不同的东西,所以使用'this.serviceFiltersPanel'将不起作用。 – Domenic

0

正常的方式做到这一点是使用绑定内部构造,但在ExtJS的 似乎有很多方法可以做到这一点,因为我从here读取。

作为一个快速常规JS砍你能做到这一点,但它不是很干:

this.serviceFiltersPanel = new Ext.FormPanel({ 
    title: 'some title', 
    layout:'anchor', 
    buttonAlign: 'left', 
    buttons: [ 
     { 

     xtype: 'button', 

     text: 'Click Me', 

     handler: (function(obj) { 

       return function(){ 
       //obj.serviceFiltersPanel refers to the FormPanel instance created. This is the real function body, 
       //the outer function is immediately executed. 
       }; 

      })(this) 
     } 
    ] 
}); 
0

有可能打的方式来做到这一点 - 这里是另一个(Ext JS的3.X)。

MyFormClass = Ext.extend(Ext.form.FormPanel, 
{ 
    /** 
    * constructor (private) - 
    */ 
    constructor: function(params) 
    { 
     var somePrivateVariable = true;  


    // A private event handler 
    var _handleClickEvent = function(cmp) { 

     // I can reference somePrivateVariable 
     // cmp is provided as a parameter 

    }.createDelegate(this); // force scope to instance of MyFormClass 


    // Remainder of constructor 
    argsForParent = {}; 
    argsForParent.collapsed = false; 
    argsForParent.width = 320; 
    argsForParent.items = [{ 
     xtype: 'button', 
     click: _handleClickEvent 
    }]; 
    argsForParent.listeners = [ ... ]; 

    // Declare my custom events 
    this.addEvents('myCustomEvent'); 

     MyFormClass.superclass.constructor.apply(this, [ argsForParent ]); 
    } }); 

Ext.reg('someXtype', MyFormClass);