在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