---
title: "Extjs自定义事件"
author: "tesia"
date: "2013-07-04T10:54:40Z"
tags: []
categories: ["Web前端"]
slug: "extjs"
draft: false
lastmod: "2013-07-04T11:54:13Z"
id: 1898317
url: "https://tesia.iteye.com/blog/1898317"
---

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无</title>
<span style="color:red"><link  rel="stylesheet" type="text/css"  href="ext-4.0.7-gpl/resources/css/ext-all.css" />
<script type="text/javascript"  src="ext-4.0.7-gpl/bootstrap.js"></script>
<script type="text/javascript" src="ext-4.0.7-gpl/locale/ext-lang-zh_CN.js"></script></span>
<script type="text/javascript">
Ext.onReady(function(){
		var Person=Ext.extend(Ext.util.Observable,{
			constructor:function(name){
				this.name=name; //this表示的是作用域，相当于指针，指向了Person的对象
				this.sayNum=0;
				//该事件的响应方法 在第3次单击say按钮时触发onSay事件 
				this.say=function(){
					if(this.sayNum<2){
						 this.sayNum+=1;
						 alert('I am '+name);
						}else{
						   // alert(0)
						    this.sayNum=0; //触发自定义事件后计数归零
						    this.fireEvent('onSay',this); //激发自定义事件 onSay是加载事件时候的事件名字							
							}
					}
					this.addEvents({"onSay":true}); //加入自定义事件
				}
			});
			 //创建对象
			window.per=new Person('tom');
			//为自定义事件绑定处理函数 
			 per.addListener('onSay',function handler(){
				 alert('发生了自定义事件');
			});

                   //为per对象添加拦截器
			<span style="color:red">Ext.util.Observable.capture(per,captureFunction);</span>
			//拦截函数
		function captureFunction(eventName){
            if(eventName=='onSay'){ //事件名称是onSay则返回  false终止事件的执行
					alert("拦截事件："+eventName+"。");
					return false;
					}
				  return true;
				}

	});
	
</script>
</head>

<body>
 <table>
 <tr>
  <td><button  type="button" id="btn"  style="width:50px;height:30px;" value="say" onclick="per.say()" >确定</button></td>
 </tr>
</table>

</body>
</html>

-----------------------
<link  rel="stylesheet" type="text/css" href="ext-4.2.1/resources/css/ext-all.css" />
<script type="text/javascript" src="ext-4.2.1/bootstrap.js"></script>
<script type="text/javascript" src="ext-4.2.1/locale/ext-lang-zh_CN.js"></script>
导入这个4.2.1的包就不可以


capture拦截器
Extjs通过capture方法为事件的执行提供了拦截器功能，给了我们控制是否执行特定事件的能力。