Http://www.cnblogs.com/pfzeng/p/4162951.html
For JavaScript custom events, the most impressive thing is when you're lazy loading a picture with jquery. Define a appear event for images that need to be lazy loaded. This custom appear event is triggered when the page image starts to appear (note that this is only triggered once).
So now we're going to talk about custom events through JavaScript.
The so-called event, the point of understanding, is to trigger a call to a function at the right time. The usual events are those that are more commonly used, bound to elements, when the user triggers a behavior (click, Focus, MouseOver, mouseout, load ...). ) This function triggers. The same is true for custom events, but it is up to you to make the trigger, such as the appear event we mentioned above, which triggers a custom method when the element is visible.
Let's simulate it with JavaScript.
//Define two methods to add an event to an element, triggering an event
1 functionAdd (EL, type, fn) {2El.listeners = El.listeners | | {}3El.listeners[type] = El.listeners[type] | | []4 El.listeners[type].push (FN)5 6El.addeventlistener (Type, FN,false);7 }8 9 functionTrigger (EL, type) {Ten if(el.listeners) { One varTriggerarr = El.listeners[type] | | []; A if(triggerarr.length) { - for(vari = 0; i<triggerarr.length; i++){ - Triggerarr[i] (); the } - } - } -}
Binds the event and triggers
1 function Dofn () { 2 alert (" Appear trigger popup!) " 3 " function DoFn2 () { 5 alert (" Appear Trigger popup 2! " 6 " 8 Add ($doTrigger," Dotrigger ", dofn) 9 Add ($doTrigger, "Dotrigger" , DOFN2) 10 Trigger ($doTrigger, "Dotrigger")
Page loads, pops up, "appear trigger popup!" "," appear triggered pop 2! "。
The implementation principle is very simple. Add an attribute listeners to the element, the default is {}, and add a type attribute with a default value of [] added to the object. When triggered, get El.listeners[type directly]. Trigger each method inside.
Easier to delete
function Remove (EL, type, fn) { if(el.listeners && El.listeners[type]) { Delete El.listeners[type] } (false)}
For the default event, we also test
Add ($clickTrigger, "click""click", CLICKFN1)
Trigger ($clickTrigger, "click")
function Clickfn () { alert ("click Trigger popup!) ")}function clickFn1 () { alert (" click Trigger popup!)} ")}
Page One load popup. Clicking on "Click event" also pops up.
Remove ($clickTrigger, "click""click", CLICKFN1)
After remove, the page load does not pop up and the click does not pop up.
Note that the above code is based on the label. We'll have time to talk about the compatibility of events later.
http://www.zhangxinxu.com/wordpress/2012/04/js-dom%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/
JavaScript event: Talk about custom events (GO)