以下代碼,定義了一個類MailRoom,並預設含有"gust"和"mail"兩個事件。
實現了:
① 添加事件
② 添加事件的響應函數
③ 觸發事件
④ 移除事件的單個響應函數
最終,用一個執行個體mailRoom驗證了MailRoom的功能。
/** * Filename: Events.js * Description: This file is user to simulate a event of javascript. * Author: 獵空de代碼 * Date: 2012/2/27 *//** * A Class with its private events. */ MailRoom = function() {this.events = ['gust', 'mail'];this.listeners = {};}// 1. addEventMailRoom.prototype.addEvent = function(eName) {if (-1 == this.events.indexOf(eName)) {this.events.push(eName);}}// 2. addListenerMailRoom.prototype.addListener = function(eName, fn) {if (!eName) {return;}if (-1==this.events.indexOf(eName)) {this.events.push(eName);this.listeners[eName] = [fn];}var arr = this.listeners[eName];if(!arr) {arr = [fn];} else {if(-1==arr.indexOf(fn)) {arr.push(fn);}}this.listeners[eName] = arr;}// 3. fireEvenMailRoom.prototype.fireEvent = function(eName) {if(!eName || -1==this.events.indexOf(eName)) {return ;}var arr = this.listeners[eName];for(var i=0; i<arr.length; i++) {var fn = arr[i];fn();}}// 4. removeListenerMailRoom.prototype.removeListener = function(eName, fn) {if(!eName || this.events.indexOf(eName)==-1) {return ;}var arr = this.listeners[eName];if(-1 != arr.indexOf(fn)) {arr.splice(arr.indexOf(fn), 1);}}// Define some shourcut.MailRoom.prototype.on = MailRoom.prototype.addListener;MailRoom.prototype.un = MailRoom.prototype.removeListener;MailRoom.prototype.fire = MailRoom.prototype.fireEvent;/** * Example */window.onload = function() {function insertInfo(sInfo) {document.body.innerHTML += sInfo + "<br />";}var mailRoom = new MailRoom();var fn1 = function() {insertInfo("605室1號床,你爸來了!");}var fn2 = function() {insertInfo("2年3班班主任,你有郵件!");}var fn3 = function() {insertInfo("605室1號床,你媽來了!");}mailRoom.on("gust", fn1);mailRoom.fire("gust");mailRoom.on("mail", fn2);mailRoom.fire("mail");mailRoom.on("gust", fn3);mailRoom.fire("gust");mailRoom.un("gust", fn3);mailRoom.fire("gust");mailRoom.on("newOne",function() {insertInfo("<br/>我是新引入的事件");})mailRoom.fire("newOne");}
運行結果:
參考自:《江湖Ext》第5章 Ext 事件系統