使用 ExtJS 就一定會自定義一些 Component 來使用,而自定義的 Component 如果要把 UI 的互動動作傳出去的話,就需要自定義 Event 了。 ### 自定義 Component 看看下面例子 : ```js Ext.define('MyApp.CustomForm', { extend: 'Ext.form.Panel', layout: { type: 'vbox' }, items:[{ xtype: 'textfield', name: 'name' }, { xtype: 'button', text: 'submit' }] }); ``` 上面定義了一個 `MyApp.CustomForm` 元件,入面定義了一個 submit button。如果要把 submit button 的 click 事件傳出去給 `MyApp.CustomForm` 接收,應該要怎樣做呢? ### 使用 `.fireEvent()` 方法 我們可以通過使用 `.fireEvent()` 方法來對元作發動事件 : ```js { xtype: 'button', text: 'submit', listeners: { click: function(ele) { ele.up('form').fireEvent('submitclick', 'message'); } } } ``` 上面的代碼是使用 `MyApp.CustomForm`發動 `submitclick` 事件,並傳入 'message' 字串作為參數。 在生成 `MyApp.CustomForm` 元件時,我們可以設定 `submitclick` 事件的 listener。 ```js var form = Ext.create('MyApp.CustomForm'); form.on('submitclick', function(message) { console.log(message); }); ``` 這樣當 `MyApp.CustomForm` 內的 `button` 按下時,`MyApp.CustomForm` 就會發動 `submitclick` 事件所連結的 listeners。