首页 技术 正文
技术 2022年11月11日
0 收藏 521 点赞 4,356 浏览 1272 个字

在JavaScript应用中事件处理是非常重要的,所有的JavaScript都是通过事件绑定到UI上的。

1. 典型用法

当事件触发的时候,事件对象event会最为回调参数传入到事件处理程序中。event对象包含所有和事件相关的信息。

1
2
3
4
5
6
7
8
9
// 不好的写法
function handleClick( event ){
var popup = document.getElementById("popup");
popup.style.left = event.clientX + "px";
popup.style.top = event.clientY + "px";
popup.className = "reveal";
// 事件处理中包含了应用逻辑
}
addListener( element,"click", handleClick );

2. 事件处理规则一:隔离应用逻辑

将应用逻辑从所有的事件处理程序中抽离出来的做法是一种最佳实践;

1
2
3
4
5
6
7
8
9
10
11
12
13
// 好的写法,拆分应用逻辑
var MyApplication = {
handleClick : function( event ){ // 事件处理
this.showPopup( event );
},showPopup : function( event ){ // 应用逻辑
var popup = document.getElementById("popup");
popup.style.left = event.clientX + "px";
popup.style.top = event.clientY + "px";
popup.className = "reveal";
}
}

3. 事件处理规则二:不要分发事件对象

上面代码存在一个问题:event对象被无节制的分发。
从匿名的事件处理函数传到 MyApplication.handleClick(),然后又传到MyApplication.showPopup()。
最佳的处理方法是让事件处理程序使用event对象来处理事件,然后拿到所有需要的数据传给应用逻辑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var MyApplication = {
handleClick : function( event ){ // 事件处理
event.preventDefault();
event.stopPropagation();
this.showPopup( event.clientX, event.clientY );
// 让事件处理程序成为接触到event对象的唯一函数。
},showPopup : function( x, y ){ // 应用逻辑
var popup = document.getElementById("popup");
popup.style.left = x + "px";
popup.style.top = y + "px";
popup.className = "reveal";
}
}

[参考资料]:
编写可维护的JavaScript,Nicholas C. Zakas 著,李晶 郭凯 张散集 译, Copyright 2012 Nicholas Zakas,978-7-115-31008-8

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774