参考网上的一个资料,做下备注。
<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>
原文地址:https://www.cnblogs.com/Fredric-2013/p/8399056.html
时间: 2024-10-12 06:45:24