4月 01, 2020 Sencha
使用 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。
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)