ExtJS - How to reference “self” in a custom function in a custom class?

别来无恙 提交于 2019-12-22 17:54:46

问题


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('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();

回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/6441502/extjs-how-to-reference-self-in-a-custom-function-in-a-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!