原生javascript有addEventListener和attachEvent方法來注冊事件,但有時候我們需要判斷某一行為甚至某一函數是否被執行了,並且能夠獲取前一行為的參數,這個時候就需要其他方法來實現了。
項目中的原始場景是有若干個tab切換,tab組件當然是已經寫好的,現在需要每次點擊后保存localstorage等其他操作,需要監聽tab是否被點擊。下面是簡單的實現事件監聽方法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件注冊</title> </head> <body> <button id="test">點擊</button> <script type="text/javascript"> var BC=(function(){ var attachFunctionList = {};
//事件通知 var notify=function(notifyName){ var args=Array.prototype.slice.call(arguments,1); attachFunctionList[notifyName].fun.apply(attachFunctionList[notifyName].scope,args); return this; }
//事件監聽 var attach = function(notifyName, callback) { if(typeof notifyName ==="string"&&typeof callback==="function"){ attachFunctionList[notifyName]={ fun:callback }; } return this; } return { attach:attach, notify:notify } })(); var $test=document.getElementById("test"); $test.onclick=function(){ var name="hz"; BC.notify("clicked",name);//按鈕點擊后通知該事件已經發生了,並把當前參數傳遞過去 }
//監聽到按鈕被點擊后進行其他操作 BC.attach("clicked",function(name){ alert("事件注冊成功!參數是:"+name); }) </script> </body> </html>