Extjs 4 MVC声明一个在整个控制器中使用的变量
在我的控制器中,我想在几个地方使用某些变量 例如,我得到了一个只有几个字段的表单(combo/textfield),我想在控制器代码的不同位置使用指向这些字段的链接。我如何/应该声明这样的变量? 我通常使用:Extjs 4 MVC声明一个在整个控制器中使用的变量,extjs,model-view-controller,extjs4,Extjs,Model View Controller,Extjs4,在我的控制器中,我想在几个地方使用某些变量 例如,我得到了一个只有几个字段的表单(combo/textfield),我想在控制器代码的不同位置使用指向这些字段的链接。我如何/应该声明这样的变量? 我通常使用: refs: [ { ref: 'myCombo', selector: 'myPanel combo[name=myCombo]' }, { ref: 'myTextfield', selector:
refs: [
{
ref: 'myCombo',
selector: 'myPanel combo[name=myCombo]'
},
{
ref: 'myTextfield',
selector: 'myPanel textfield[name=myTextfield]'
}
]
但是每次我必须在控制器中处理这些字段时,可以使用getMyCombo()/getMyTextfield()吗?控制器的“refs”功能实际上只是通过使用Ext.ComponentQuery
和提供的CSS选择器来为您生成getter函数。您使用它们的方式是使用系统的一种方式,尽管您也可以使用refs
使用其配置的alias
或xtype
为控制器实例化(例如)视图。在您的示例中,您省去了重新编写一些冗长的ComponentQuery
调用的麻烦
“autoCreate”选项虽然没有文档记录,但对于这类事情非常有用。例如,如果希望每次激活控制器时都实例化某个对象的新实例,可以在init()函数中这样做
演示如何使用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 */
});
}
});