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

Cha*_*hau 2 scope extjs extend

我正在努力扩展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
            }
        ]
    })
});
Run Code Online (Sandbox Code Playgroud)

我还没有学到的是为什么不允许这样做.this在全球范围指点,而不是我的扩展面板-因而.method()undefined处理函数里面.

ob1*_*ob1 6

您在原型上而不是在特定对象上定义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
    }
});
Run Code Online (Sandbox Code Playgroud)

有关可在扩展组件时使用的模板,请参阅http://www.sencha.com/learn/Manual:Component:Extending_Ext_Components