Extjs 如何在扩展时初始化新元素 - 不丢失范围
我试图更好地扩展 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
。
I am trying to get better at extending the classes of Extjs, and my evolvement have lead me to this problem:
I have extended an Ext.Panel and I want my extension to have a bottom toolbar with one button as default.
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
}
]
})
});
What I haven't learnt yet is why this is not allowed. this
is pointing at the global scope and not my extended panel - thus .method()
is undefined
inside the handler function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在原型上而不是在特定对象上定义 bbar。
重写 initComponent 并将 bbar 定义移至其中。
请参阅http://www.sencha.com/learn/Manual:Component:Extending_Ext_Components 扩展组件时可以使用的模板
You're defining the bbar on the prototype rather than on a specific object.
Override initComponent and move the bbar definition inside it.
See http://www.sencha.com/learn/Manual:Component:Extending_Ext_Components for a template you can use when extending components
您必须记住,作为
items
数组的第一个元素的匿名对象是在与Ext.extend(...
的范围相同的范围内创建的) > 被执行,如果您有这样的情况:
您会期望
oa
、ob
和o.scope
具有与相同的值。当前作用域中的 >a
、b
和this
在这里,情况有点复杂,因为您在创建数组的同时创建对象。对象等,但推理是相同的,您应该做的是在构造函数中定义
this.bbar
:You have to keep in mind that the anonymous object that is the first element of the
items
array is created in the same scope as the one in whichExt.extend(...
is executed.If you had this:
you would expect that
o.a
,o.b
, ando.scope
would have the same values asa
,b
, andthis
in the current scope. Here, it's a little more complex because you are creating an object while creating an array while creating an object, etc., but the reasoning is the same.What you should do instead is define
this.bbar
inside the constructor: