Ext中遵循一种树状的事件模型,所有继承自Ext.util.Observable类的控件都可以支持事件,可以为这些继承了Ext.util.Observable的对象定义一些事件,然后为这些时间配置监听器,当某个事件被触发时,Ext会自动调用对应的监听器,这些就是Ext的事件模型。
如:定义Person类
///<reference path="../../ext-3.2.0/adapter/ext/ext-base-debug.js"/> ///<reference path="../../ext-3.2.0/ext-all-debug.js"/> Person = function(name) { this.name = name; this.addEvents("walk", "eat", "sleep"); } Ext.extend(Person, Ext.util.Observable, { info: function(event) { return this.name + "is" + event + "ing."; } });
为Person添加事件监听器这里的on()是addListener()的简写形式,功能完全一样,第一个参数传递的是事件名称,第二个参数是事件发生时执行的函数,为简单期间,在这里全部写成alert形式。var person = new Person("Someone"); person.on("walk", function() { Ext.Msg.alert('Event', person.name + "在走啊走啊。"); }); person.on("eat", function(breakfast, lunch, supper) { Ext.Msg.alert("Event", person.name + "要吃" + breakfast + "," + lunch + "和" + supper + "。"); }); person.on("sleep", function(time) { Ext.Msg.alert("Event", person.name + "从" + time.format("H") + "点开始睡觉了。"); });
触发Person的事件,代码如下
<!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> <title>Ext事件</title> <link rel="Stylesheet" type="text/css" href="../ext-3.2.0/resources/css/ext-all.css" /> <script type="text/javascript" src="../ext-3.2.0/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="../ext-3.2.0/ext-all.js"></script> <!--导入中文语言包--> <script type="text/javascript" src="../ext-3.2.0/ext-lang-zh_CN.js" charset="urf-8"></script> <script type="text/javascript" src="js/Person.js"></script> <script type="text/javascript"> Ext.onReady(function() { Ext.get("walk").on("click", function() { person.fireEvent("walk"); }); Ext.get("eat").on("click", function() { person.fireEvent("Eat", "早餐", "中餐", "晚餐"); }); Ext.get("sleep").on("click", function() { person.fireEvent("Sleep", new Date()); }); }); </script> </head> <body> <input type="button" id="walk" value="Walk" /><br /> <input type="button" id="eat" value="Eat" /><br /> <input type="button" id="sleep" value="Sleep" /> </body> </html>