通過使用Ext.ComponentQuery
和提供的CSS selector
,控制器的「參考」功能實際上只是爲您生成吸氣功能。您使用它們的方式是您可以使用該系統的一種方式,但您也可以使用refs
爲控制器實例化(例如)使用其配置的alias
或xtype
的視圖。在你的例子中,你可以省去重寫一些長期呼叫的麻煩。
'autoCreate'選項雖然沒有文檔說明,但對於這種類型的東西來說非常適合,例如,如果您希望每次激活控制器時總是實例化某個對象的新實例,則可以在init ()函數。
The answer posted here演示如何使用refs
創建新實例並進一步解釋autoCreate
和forceCreate
選項的功能。
如果你想使用一個對象或整個控制器的一些變量,只是在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 */
});
}
});