JavaScript 設計自己的事件

來源:互聯網
上載者:User

以下代碼,定義了一個類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 事件系統

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.