[英]Why extjs button handler doesn't work
單擊“取消”后,我有一個包含一些按鈕的窗口沒有任何反應。 我真的很困惑我可能會出錯:
Ext.define('Myapp.view.User.NewForm', {
extend: 'Ext.window.Window',
width: 610,
height: 380,
y: 50,
resizable: false,
closable: true,
draggable: false,
title: 'new user',
items: [{
buttons: [{
text: 'save',
iconCls: 'form-save'
},{
text: 'cancel',
iconCls: 'form-cancel',
scope: this,
handler: this.cancel
}]
}],
cancel: function() { alert('cancel'); }
})
就像Lolo所說,在定義Form類時, this.cancel
是未定義的。
解決此問題的標准方法是在initComponent
內創建items
數組:
Ext.define('Myapp.view.User.NewForm', {
...
initComponent: function() {
this.items = [{
buttons: [{
text: 'save',
iconCls: 'form-save'
},{
text: 'cancel',
iconCls: 'form-cancel',
scope: this,
handler: this.cancel
}]
}];
this.callParent();
},
cancel: function() { alert('cancel'); }
});
當調用initComponent
, this
指向您期望的Form的實例。 在您的代碼中, this
指向不包含cancel函數的全局window
對象。
您也可以通過這種方式定義窗口按鈕
...
initComponent: function(){
this.buttons = [
{ text:'Close',
handler: function(){
this.up('window').close(); //<--Notice "this" refers to the button
}
},
{
text: 'Save',
action: 'save',
handler: this.save,
scope: this
}
]; //eo buttons
this.callParent(arguments);
}, //eo initComponent
save: function(){ ... }
...
那是因為this.cancel未定義。 看到這段代碼:
var that = this;
Ext.define('Myapp.view.User.NewForm', {
items: [{
buttons: [{
text: 'save',
iconCls: 'form-save'
},{
text: 'cancel',
iconCls: 'form-cancel',
scope: this, // that === this
handler: this.cancel
}]
}],
cancel: function() { alert('cancel'); }
})
這傳遞給范圍指向與該變量相同的對象。 您必須找到其他方式來獲取對父控件的引用。 您可以嘗試: handler: function(){ this.ownerCt.ownerCt.cancel.apply(this, arguments); }
handler: function(){ this.ownerCt.ownerCt.cancel.apply(this, arguments); }
,並刪除scope: this
行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.