Extjs如何在扩展时初始化新元素-而不丢失范围

Extjs如何在扩展时初始化新元素-而不丢失范围,extjs,scope,extend,Extjs,Scope,Extend,我试图更好地扩展Extjs的类,我的发展导致了这个问题: 我扩展了一个Ext.Panel,我希望我的扩展有一个底部工具栏,默认为一个按钮 myPanel = Ext.extend(Ext.Panel, { method: function () { return 'response!'; }, bbar: new Ext.Toolbar({ items: [ { xt

我试图更好地扩展Extjs的类,我的发展导致了这个问题:

我扩展了一个Ext.Panel,我希望我的扩展有一个底部工具栏,默认为一个按钮

myPanel = Ext.extend(Ext.Panel, {
    method: function () {
        return 'response!';
    },

    bbar: new Ext.Toolbar({
        items:
        [
            {
                xtype: 'button',
                text: 'Hit me!',
                handler: function (button, event) {
                    alert(this.method());
                },
                scope: this
            }
        ]
    })
});

我还不知道为什么这是不允许的
指向全局范围,而不是我的扩展面板-因此
.method()
在处理程序函数中是
未定义的

您在原型上定义bbar,而不是在特定对象上

重写initComponent并将bbar定义移动到其中

myPanel = Ext.extend(Ext.Panel, {
    method: function () {
        return 'response!';
    },

    initComponent: function() {    
        var bbar = new Ext.Toolbar({
            items:
            [
                {
                    xtype: 'button',
                    text: 'Hit me!',
                    handler: function (button, event) {
                        alert(this.method());
                    },
                    scope: this
                }
            ]
        });

        // Config object has already been applied to 'this' so properties can 
        // be overriden here or new properties (e.g. items, tools, buttons) 
        // can be added, eg:
        Ext.apply(this, {
            bbar: bbar
        });

        // Call parent (required)
        myPanel.superclass.initComponent.apply(this, arguments);

        // After parent code
        // e.g. install event handlers on rendered component
    }
});

有关扩展组件时可以使用的模板,请参见。您必须记住,作为
数组的第一个元素的匿名对象是在与执行
Ext.extend(…
的数组相同的范围内创建的

如果你有这个:

var o = { 'a': a, 'b': b, scope: this };
您可能希望
o.a
o.b
o.scope
与当前范围内的
a
b
this
具有相同的值。在这里,它稍微复杂一些,因为您在创建对象的同时创建一个数组,等等,但推理是相同的。

相反,您应该在构造函数中定义
this.bbar

myPanel = Ext.extend(Ext.Panel, {
    method: function () {
        return 'response!';
    },

    constructor: function(config) {
        this.bbar = new Ext.Toolbar({
            items:
            [
                {
                    xtype: 'button',
                    text: 'Hit me!',
                    handler: function (button, event) {
                        alert(this.method());
                    },
                    scope: this
                }
            ]
        });

        myPanel.superclass.constructor.apply(this, arguments);
    }
});