參考網上的一個資料,作下備註。javascript
<html> <head> <title>js event demo</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0" max-age="0"> </head> <body> <h4>js event demo</h4> </body> <script type="text/javascript"> //自定義事件 function EventEmitter() { this.events = {}; } //綁定事件函數 EventEmitter.prototype.on = function(ename, call){ this.events[ename] = this.events[ename] || []; this.events[ename].push(call); } EventEmitter.prototype.emit = function(ename, _){ var events = this.events[ename]; //取參數,剔除參數ename var args = Array.prototype.slice.call(arguments, 1); for(var i = 0; i < events.length; i++){ //調用綁定的事件函數 events[i].apply(null, args); } } function app(){ calltime = 0; //同一個事件綁定了兩個處理函數 this.on('start',function(user, date){ calltime += 1; console.log('event start: ' + user + " " + date + " " + calltime); }); this.on('start', function(user, date){ calltime += 1; console.log('event start: ' + user + " " + date + " " + calltime); }) } app.prototype = new EventEmitter(); var a = new app(); //觸發事件 a.emit('start', 'fred', new Date()); </script> </html>