2013-12-10 28 views
0

在我的控制器中,我想在幾個地方使用某些變量。Extjs 4 MVC聲明一個變量用於整個控制器中

例如,我得到了一個幾個字段(組合/文本字段)的表單,我想在我的控制器代碼的各個地方使用它們的鏈接。我該如何/應該宣佈這樣的變量? 通常我使用:

refs: [ 
    { 
     ref: 'myCombo', 
     selector: 'myPanel combo[name=myCombo]' 
    }, 
    { 
     ref: 'myTextfield', 
     selector: 'myPanel textfield[name=myTextfield]' 
    } 
] 

但它是確定使用getMyCombo()/ getMyTextfield()每次我有我的控制器這個領域的工作時間?

回答

1

通過使用Ext.ComponentQuery和提供的CSS selector,控制器的「參考」功能實際上只是爲您生成吸氣功能。您使用它們的方式是您可以使用該系統的一種方式,但您也可以使用refs爲控制器實例化(例如)使用其配置的aliasxtype的視圖。在你的例子中,你可以省去重寫一些長期呼叫的麻煩。

'autoCreate'選項雖然沒有文檔說明,但對於這種類型的東西來說非常適合,例如,如果您希望每次激活控制器時總是實例化某個對象的新實例,則可以在init ()函數。

The answer posted here演示如何使用refs創建新實例並進一步解釋autoCreateforceCreate選項的功能。

如果你想使用一個對象或整個控制器的一些變量,只是在init方法設置控制器上的屬性,最適合...

Ext.define('App.controller.Messaging', { 
    /** Include models, stores, views, etc... */ 
    refs: [{ 
     ref: 'messageBox', // creates magic method "getMessageBox" 
     xtype: 'my-messagebox', // in the class file: alias: 'widget.my-messagebox' 
     selector: '', // could be itemId, name, etc. Same rules as a CSS selector 
     autoCreate: true // automatically create when "getMessageBox()" is called 
    }], 

    /** I always initialize controllers as-needed, passing the application object */ 
    init: function(app){ 
     var me = this; 

     // Initialize whatever you need, maybe set up some controller properties 
     this.eventBus = app.getEventBus(); 
     this.user  = app.getActiveUser(); 

     // I prevent listeners from being established twice like this.. 
     if(this.inited === true) 
      return; 

     this.inited = true; // nothing past this line will be executed twice 

     // Observe view events 
     this.control(); 

     // Listen for application events 
     app.on({ 
      'getMessages': {fn: me.showMessageBox, scope: me} 
     }); 

     // Specific controller events 
     this.on({ 
      'someEvent': {fn: me.someFunction, scope: me} 
     }); 

    }, 

    // A function using controller properties defined in the init() method 
    someFunction = function(){ 
     var me = this; // controller 

     // Lets show the active user 
     console.warn("Active User", me.user); 

     // And then fire an event, passing this controller 
     me.eventBus.fireEvent('somethingHappened', me); 
    }, 

    // Invoked on the application event "getMessages" 
    showMessageBox: function(sessionId){ 
     var me = this; // controller 

     /** ... Load the messages for the provided sessionId ... */ 

     // Then create an instance of the message box widget as property on the controller 
     me.messageBox = me.getMessageBox({ 
      /** pass config to the view here if needed */ 
     }); 
    } 
});