如何让ViewController事件处理程序将"this"设置为ExtJS中的视图



默认情况下,在ExtJS中,当创建一个视图和关联的控制器,然后定义类似myevent: 'onEvent'的事件时,控制器中的onEvent将以this为viewController执行。

是否可以将this作为视图?

您想要的方式是不可能开箱即用的。但是,您可以在视图呈现后设置侦听器的范围。Fiddle以供参考。

Ext.define('MyViewController', {
extend: 'Ext.app.ViewController',
alias: 'controller.myView',
onAfterRenderView: function(view) {
view.on({
customEvent: this.onCustomEventView,
// Notice what we're using as the scope here
scope: view
});
},
onClickCustomEventBtn: function() {
this.getView().fireEvent('customEvent');
},
onCustomEventView: function() {
console.log(this);
}
});

为了增加一点颜色,组件上有defaultListenerScope的想法,它允许您在视图定义上创建内联处理程序,而不必创建ViewController。在这种情况下,如果在具有ViewController的类中使用此类,则可以控制listeners块中的scope属性。我在API文档中找不到这个属性的定义,但视图控制器指南对此进行了解释

如果我们的按钮类看起来像这样:

Ext.define('ChildButton', {
extend: 'Ext.button.Button',
alias: 'widget.myButton',
// If we want class's to have handlers resolve to itself, this must be set
defaultListenerScope: true,
text: 'Fire Custom Event',
onClickCustomEventBtn: function() {
console.log('Firing from button class');
this.ownerCt.ownerCt.fireEvent('customEvent');
}
});

我们这样实例化它:

dockedItems: [{
xtype: 'toolbar',
dock: 'top',
items: [{
xtype: 'myButton',
listeners: {
// If set to this, it'll use the class's handler def
// If set to controller, it'll resolve to using the VC's def
scope: 'this',
click: 'onClickCustomEventBtn'
}
}]
}]

我们希望框架在ChildButton类中查找onClickCustomEventBtn,因为我们设置了scope: 'this'。。。如果我们简单地删除scope或将其设置为'controller',那么它将解析为MyViewController中的处理程序。

最新更新