如何在类中定义的自定义函数中引用自定义类的实例?
我通过ExtJS4的类扩展“机制”扩展了一个类,我有一个自定义事件处理程序,当触发某些东西时会调用它,我想在触发某些东西时折叠Panel。
但是,在下面的Reactor类的事件处理程序中,“this”引用EventTriggerer(事件的firer)而不是Reactor的实例。如何在自定义函数中引用EventReactor的实例?
谢谢! DashK
Ext.define('EventReactor', {
extend: 'Ext.panel.Panel',
onSomething: function(data) {
// ERROR
// this.collapse is undefined. "this" actually references EventTriggerer
this.collapse();
}
});
Ext.define('EventTriggerer', {
extend: 'Ext.util.Observable',
singleton: true,
constructor: function() {
this.addEvents({
"changedView" : true
});
},
doSomething: function() {
// Do some stuff
this.fireEvent("doneSomething", data);
}
});
...
// Here's how the listeners are added
var er = Ext.create('EventReactor');
EventTriggerer.addListener("doneSomething", er.onSomething);
// Here's how the event is triggered.
er.doSomething();
答案 0 :(得分:9)
您应该在构造函数执行期间创建一个嵌套范围来存储“this”:
Ext.define('EventReactor', function() {
var self; // This is a variable to store "this"
return {
extend: 'Ext.panel.Panel',
constructor: function() {
self = this; // Here you store "this" in the closure
self.callParent(arguments);
},
onSomething: function(data) {
// ERROR
// this.collapse is undefined. "this" actually references EventTriggerer
// this.collapse();
// Using "self" instead of "this" => No error
self.collapse();
}
};
});
详细信息(请参阅define方法):http://docs.sencha.com/ext-js/4-1/#!/api/Ext
答案 1 :(得分:0)
addListener()方法有一个额外的参数scope
,可以设置为在事件处理程序中变为this
的对象。
EventTriggerer.addListener("doneSomething", er.onSomething, er);