2

我正在尝试更好地扩展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
            }
        ]
    })
});

我还没有学到的是为什么这是不允许的。this指向全局范围,而不是我的扩展面板 - 因此.method()位于undefined处理函数内部。

4

2 回答 2

7

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

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

于 2010-06-30T14:34:55.960 回答
1

您必须记住,作为items数组第一个元素的匿名对象是在与执行对象相同的范围内创建的Ext.extend(...

如果你有这个:

var o = { 'a': a, 'b': b, scope: this };

您会期望 , o.a,o.b和在当前范围内具有与, , ando.scope相同的值。这里稍微复杂一些,因为你是在创建对象的同时创建一个数组,同时创建一个对象等等,但是推理是一样的。abthis

你应该做的是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);
    }
});
于 2010-06-30T14:36:30.590 回答