How do I reference an instance of a custom class inside a custom function defined within the class?
I've extended a class through ExtJS4's class extension "mechanism", and I've a custom event handler that will be called when something is triggered, and I want to collapse the Panel when something is fired.
However, in the event handler of the Reactor class below, "this" references EventTriggerer (The firer of the event) instead of the instance of the Reactor. How do I reference the instance of the EventReactor inside a custom function?
Thanks! DashK
Ext.define('EventReactor', {
extend: 'Ext.panel.Panel',
onSomething: function(data) {
// ERROR
// this.collapse is undefined. "this" actually references EventTriggerer
this.collapse();
}
});
Ext.define('EventTr开发者_C百科iggerer', {
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();
You should create a nested scope to store "this" during constructor execution:
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();
}
};
});
Detailed information (see define method): http://docs.sencha.com/ext-js/4-1/#!/api/Ext
The addListener() method has an additional parameter scope
that can be set to an object that becomes this
in the event handler.
EventTriggerer.addListener("doneSomething", er.onSomething, er);
精彩评论