您的位置:首页 > Web前端

一个简单的前端事件框架

2018-02-01 15:00 309 查看
参考网上的一个资料,做下备注。

<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: