【小记录】关于dojo中的on事件
今天碰到一个现象,若是一个函数中存在一个on事件(例如点击事件),在该函数连续触发两次之后在去触发里面的on事件,会发现改时间所对应的函数被调用了两次,若父函数被连续触发N次后再取触发on事件,其对应的函数会被调用N次。然后JS原生的事件不会有此现象。对比代码如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/> <title>Simple Map</title> <script type="text/javascript" src="http://localhost:8080/gisapi/library/3.9/3.9/init.js"></script> </head> <body> <button id="test1">test1</button> <button id="test2">test2</button> <script type="text/javascript"> require(["dojo/on"], function (on) { var oTest1 = document.getElementById("test1"); var oTest2 = document.getElementById("test2"); on(oTest1, "click", function () { alert(1); on(oTest2, "click", function () { alert(2); }); }); }); </script> </body> </html>
(上面我用了arcgis for javascript的本地api,没有的朋友可以改成dojo的api)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/> <title>Simple Map</title> </head> <body> <button id="test1">test1</button> <button id="test2">test2</button> <script type="text/javascript"> var oTest1 = document.getElementById("test1"); var oTest2 = document.getElementById("test2"); oTest1.onclick = function () { alert(1); oTest2.onclick = function () { alert(2); } } </script> </body> </html>
总结:若函数中有dojo的on事件,每次执行函数后on事件都会呈现出“预触发”的状态,该函数每次执行一次该状态都会+1,等到触发了on事件,“预触发”状态会转变为“被触发“状态(有几此”预触发“状态就会触发几次,虽然我们只是触发了一次该事件)。其中要主要的是,只要执行了函数,”预触发“状态都会被+1,和期间有没有触发on事件无关。
----------------------------------------------------------------------更新----------------------------------------------------------------------
之后我又发现另外一个现象,如果把on事件中的函数单独的外面封装后再引用的话,其输出效果便为正常,即没有“预触发”状态这一说法。事例程序如下:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/> <title>Simple Map</title> <script type="text/javascript" src="http://localhost:8080/gisapi/library/3.9/3.9/init.js"></script> </head> <body> <button id="test1">test1</button> <button id="test2">test2</button> <script type="text/javascript"> require(["dojo/on"], function (on) { var n = 0; var oTest1 = document.getElementById("test1"); var oTest2 = document.getElementById("test2"); on(oTest1, "click", function () { on(oTest2, "click", test); alert(1); }); function test () { alert(2); } }); </script> </body> </html>
Stick to write blog!