会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
Lonsan
博客园
首页
博问
闪存
新随笔
订阅
管理
JS类中event的简单实现(续)
JS中的事件处理,在上次的基础上进行了修改,已经支持+=和-=操作符,但是还存在一些问题,正寻求解决方法。
<!--
description:JS类中event的简单实现2
code by Lonsan on 2005
email:Lonsan21@163.com
请各位多批评指导,谢谢
-->
<
html
>
<
head
>
<
title
>
JS Event2
</
title
>
<
style
>
</
style
>
</
head
>
<
body
>
</
body
>
</
html
>
<
script
language
="javascript"
>
<!--
//
实现,实现类似C#风格调用
//
已经支持+=和-=操作符,但是还存在很多问题,正寻求解决方法
//
注:参考了birdshome提示,在此表示感谢。
function
RaiseEvent(sender,event)
{
var
funs
=
""
;
for
(
var
k
in
EventHandler.Events)
{
if
(k
==
"
length
"
)
continue
;
if
((event
&
EventHandler.Events[k].ID)
>
0
)
{
funs
+=
k
+
"
(sender);\n
"
;
}
}
eval(
"
var f = function(sender){\n
"
+
funs
+
"
\n}
"
);
f(sender);
}
function
EventHandler(o)
{
this
.EventID;
var
fname;
if
(
typeof
o
==
"
function
"
)
{
fname
=
o.toString().match(
/
function
([
^
\
0
\(]
*
)\(
/
)[
1
];
if
(EventHandler.Events[fname]
==
null
)
{
this
.EventID
=
(
1
<<
EventHandler.Events.length);
EventHandler.Events[fname]
=
{ID:
this
.EventID}
;
EventHandler.Events.length
++
;
}
else
{
this
.EventID
=
EventHandler.Events[fname].ID;
}
}
}
EventHandler.Events
=
{length:
0
}
;
EventHandler.Null
=
0
;
EventHandler.prototype.toString
=
function
()
{
return
this
.EventID;
}
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
示例
function
Persion()
{}
Persion.prototype.onBeginSpeak
=
EventHandler.Null;
Persion.prototype.name
=
"
Lonsan
"
;
Persion.prototype.Speak
=
function
(sWords)
{
RaiseEvent(
this
,
this
.onBeginSpeak);
alert(
"
正在讲话。。。\n以下是讲话内容:\n
"
+
sWords);
}
var
p
=
new
Persion()
//
test1
p.onBeginSpeak
+=
new
EventHandler(BeginSpeak1);
p.onBeginSpeak
+=
new
EventHandler(BeginSpeak2);
alert(
"
测试1开始!!
"
);
p.Speak(
"
大家好,我是
"
+
p.name
+
"
。
"
);
//
test2
p.onBeginSpeak
-=
new
EventHandler(BeginSpeak2);
p.onBeginSpeak
+=
new
EventHandler(BeginSpeak3);
alert(
"
测试2开始!!
"
);
p.Speak(
"
第二次\n已经取消BeginSpeak2事件。\n我是
"
+
p.name
+
"
。
"
);
function
BeginSpeak1(sender)
{
alert(
"
处理BeginSpeak事件!--1\n
"
);
}
function
BeginSpeak2(sender)
{
alert(
"
处理BeginSpeak事件!--2
"
);
}
function
BeginSpeak3(sender)
{
sender.name
=
"
(Lonsan)蓝山
"
;
alert(
"
处理BeginSpeak事件!--3
"
);
}
//
-->
</
script
>
posted on
2005-04-08 13:11
蓝山
阅读(
1322
) 评论(
5
)
收藏
举报
刷新页面
返回顶部