ExtJS - 如何引用“自我”在自定义类中的自定义函数? [英] ExtJS - How to reference "self" in a custom function in a custom class?

查看:389
本文介绍了ExtJS - 如何引用“自我”在自定义类中的自定义函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在类中定义的自定义函数中引用自定义类的实例?

How do I reference an instance of a custom class inside a custom function defined within the class?

我通过ExtJS4的类扩展机制扩展了一个类,我有一个自定义事件处理程序,当触发某些东西时会调用它,我想在触发某些东西时折叠Panel。

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.

但是,在事件中下面的Reactor类的处理程序,this引用EventTriggerer(事件的firer)而不是Reactor的实例。如何在自定义函数中引用EventReactor的实例?

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?

谢谢!
DashK

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


推荐答案

您应该创建一个嵌套范围来存储this在构造函数执行期间:

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

详细信息(请参阅define方法): http://docs.sencha.com/ext-js/4-1/#!/api/Ext

Detailed information (see define method): http://docs.sencha.com/ext-js/4-1/#!/api/Ext

这篇关于ExtJS - 如何引用“自我”在自定义类中的自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆