2011-11-18 110 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);