2011-12-08 58 views
1

点击“取消”后,我有一个包含一些按钮的窗口什么也没有发生。 我真的很困惑什么可能我得到错误:为什么extjs按钮处理程序不起作用

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'); } 

}) 

回答

2

就像Lolo说的那样,this.cancel在定义Form类时是未定义的。

这个问题的标准解决方案是创建items阵列内initComponent

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点到窗体的实例为人们所期望的。在您的代码this指向全局window对象,其中不包含取消功能。

0

这是因为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); },并删除scope: this一行。

1

您也可以定义你的窗口按钮,这样

... 
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(){ ... } 
...