当前位置:首页 > 编程笔记 > 正文
已解决

javascript自定义事件的观察者模式写法和用法以及继承

来自网友在路上 11058105提问 提问时间:2023-11-07 08:10:33阅读次数: 105

最佳答案 问答题库1058位专家为你答疑解惑

<html><head><meta http-equiv="Context-Type:text/html;charset=utf-8"/><title>自定义事件之观察者模式</title><script type="text/javascript" src="common.js"></script></head><body><input type="button" name="btn" value="点击" id="mybtn"/><script type="text/javascript">//继承关系函数function inherit(sub,sup){var prototype=Object(sup.prototype);prototype.constructor=sub;sub.prototype=prototype;}//父类函数function EventTarget(){this.handlers={};}//父类函数的原型方法EventTarget.prototype={//使用字面量对象的原型方法必须加上构造函数原自父类,不然字面量原型方法就继承于object对象constructor:EventTarget,//注册自定义事件,也就是自定义事件的处理的函数addHandler:function(type,handler){if(typeof this.handlers[type] =="undefined"){this.handlers[type]=[];}this.handlers[type].push(handler);},//执行自定义事件的函数,也就是触发自定义事件的函数fire:function(event){if(!event.target){event.target=this;console.log(event);}if(this.handlers[event.type] instanceof Array){var handlers=this.handlers[event.type];//console.info(handlers);for(var i=0;i<handlers.length;i++){handlers[i](event);}}},//删除自定义事件函数removeHandler:function(type,handler){if(this.handlers[type] instanceof Array){var handlers=this.handlers[type];for(var i=0;i<handlers.length;i++){if(handlers[i]===handler){break;}}handlers.splice(i,1);}}};//子类function Person(name,age){EventTarget.call(this);this.name=name;this.age=age;}//子类继承父类inherit(Person,EventTarget);//执行自定义事件函数Person.prototype.say=function(message){//type表示你自定义事件的种类,message表示触发后的信息this.fire({type:"message",message:message});}//执行自定义的事件的函数Person.prototype.data=function(event,str){//这里type同样表示自定义事件的种类,event表示传递过来的事件,data:str表示传递的数据this.fire({//event这里表示从re()函数的btn事件中传递过来的点击事件type:'data',x:event.clientX,y:event.clientY,data:str});};//getna事件,获取person的name\agePerson.prototype.getna=function(arr){this.fire({type:'getna',getna:arr});}//一般事件信息处理函数function hm(event){alert("message received: "+event.message);}//这里re(event)中的event表示从data事件中传递过来的event//处理点击事件带数据的函数function re(event){var ss=event;btn.onclick=function(event){var event=EventUtil.getEvent(event);var target=EventUtil.getTarget(event);alert(event.x+":"+event.y);console.info(ss.data);}}//处理getna事件的函数function getnameage(event){alert(event.getna);}//创建实例var person=new Person('Nicholas',23);//注册一般事件信息person.addHandler("message",hm);//注册点击事件,获取点击的坐标person.addHandler('data',re);//触发一般事件的信息person.say("Hi i am here");var btn=document.getElementById('mybtn');//触发带数据的点击事件person.data('','dfd');//先注册getna事件person.addHandler('getna',getnameage);//然后触发getna事件的函数person.getna([person.name,person.age]);</script></body>
</html>
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"javascript自定义事件的观察者模式写法和用法以及继承":http://eshow365.cn/6-34376-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!