JS scope Problem
how to i access "myhandler" from within "title->tbar->item->handler:
Application.MenuPanel = Ext.extend(Ext.Panel, {
title: 'Standard',
tbar: [{
xtype: 'buttongroup',
columns: 3,
title: 'MyTitle',
items: [{
text: 'Addl',
scale: 'large',
rowspan: 3, iconCls: 'add',
iconAlign: 'top',
cls: 'x-btn-as-arrow',
handler: this.myHandler.createDelegate(this, ['Hello World']) // <-- How to acces myHandler()?
},
{
text: 'D开发者_开发问答elete',
scale: 'large',
rowspan: 3, iconCls: 'delete',
iconAlign: 'top',
cls: 'x-btn-as-arrow'
},
]
}]
,myHandler : function (name) {
Ext.Msg.alert('Inside', 'Hello ' + name);
}
});
Error:
this.myHandler is undefined [Break on this error] handler: this.myHandler.createDelegate(this, ['Hello World'])
in the second argument of extend, you are declaring an object that will be merged into the prototype of your class.
In your statement, this is resolved during declaration process, not during instanciation. Therefore, this refers to the context where you declared this class, and not to a future instance of it.
You should assign the handler in the constructor. I don't know which name it has in ExtJs but it could be something like initialize:
Application.MenuPanel = Ext.extend(Ext.Panel, {
title: 'Standard',
tbar: null,
initialize: function() {
this.myHandler.createDelegate(this, ['Hello World']);
this.tbar = [{
xtype: 'buttongroup',
columns: 3,
title: 'MyTitle',
items: [{
text: 'Addl',
scale: 'large',
rowspan: 3, iconCls: 'add',
iconAlign: 'top',
cls: 'x-btn-as-arrow',
handler: this.myHandler.createDelegate(this, ['Hello World'])
},
{
text: 'Delete',
scale: 'large',
rowspan: 3, iconCls: 'delete',
iconAlign: 'top',
cls: 'x-btn-as-arrow'
},
]
}];
},
myHandler : function (name) {
Ext.Msg.alert('Inside', 'Hello ' + name);
}
}
note: only assign primitives types ( strings, integer ) in the prototype because objects properties won't be cloned, therefore any instances will share the same reference. This is desirable for functions only, generally.
Final and working solution. Thanks BiAiB.
Application.MenuPanel = Ext.extend(Ext.Panel, {
title: 'Standard',
tbar: null,
initComponent: function() {
Ext.apply(this, {
tbar : [{
xtype: 'buttongroup',
columns: 3,
title: 'MyTitle',
items: [{
text: 'Addl',
scale: 'large',
rowspan: 3, iconCls: 'add',
iconAlign: 'top',
cls: 'x-btn-as-arrow',
handler: this.myHandler.createDelegate(this, ['Hello World'])
},
{
text: 'Delete',
scale: 'large',
rowspan: 3, iconCls: 'delete',
iconAlign: 'top',
cls: 'x-btn-as-arrow'
},
]
}]
})
Application.MenuPanel.superclass.initComponent.apply(this, arguments);
},
myHandler : function (name) {
Ext.Msg.alert('Inside', 'Hello ' + name);
}
});
精彩评论