In the previous article of the event binding method, I believe you have seen it.
But here's a little bit of a problem, these methods, the variables are global, it will inevitably conflict with other libraries or methods to be overwritten, so I made a small package here, as follows:
JavaScript Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
(function(window) { varYx =function(){ } Yx.evguid =0; //Bind Event Yx.prototype. bind =function(Ele/ * Tag Element Object * /, Evname/ * Method name, without an on prefix * /, Evfunc/ * method * /){ if(!evfunc.$ $guid) evfunc.$ $guid = yx.evguid++;//Add an identity to the newly added event if(!ele.events) ele.events = {};//Add an event collection for an element Evname = Evname; if(!ele.events[evname]) { Ele.events[evname] = {}; } if(ele.events[evname][evfunc.$ $guid]==undefined) ele.events[evname][evfunc.$ $guid] = {}; ele.events[evname][evfunc.$ $guid] = Evfunc; ele["on"+evname] = EventManager;//Event Unification Processing } //Unbind Event Yx.prototype. Unbind =function(Ele/ * Tag Element Object * /, Evname/ * Method name, without an on prefix * /, Evfunc/ * method * /) { if(ele.events && Ele.events[evname]) { Deleteele.events[evname][evfunc.$ $guid]; } } //Event Management /* Here is the entry function for all events, all calling this function, and then calling the corresponding function through it. */ functionEventManager (e) { varSelf = This;//Current Object vare = e | | window.event;//event Object if(!e.stoppropagation) {block default behavior under//ie, event bubbling E.preventdefault =function() { This. returnvalue =false;} E.stoppropagation =function() { This. cancelbubble =true;} } varEvfuncs = Self.events[e.type];//Gets the current object, specifying the event name event array for(varKeyinchEvfuncs) { Evfuncs[key] (e); } } Window.yx =NewYx (); }) (window); |
JavaScript Code
| 1 |
|
(function(window) {/*...*/}) (window); |
This is a self-executing function that executes immediately after the function is created, often used to create namespaces
JavaScript Code
In this case, the YX variable is defined here under window, which is an object of the class Yx, which defines a global variable called YX, so that we can invoke the corresponding method through Yx.xxx. The syntax is as follows:
JavaScript Code
1 2 3 4 5 6 7 |
  |
var item = document.getelementbyid ( "test" yx.bind (item, ,  function (e) { //console.log ("div click 1 !"); alert ( "div click 1 !" ); e.stoppropagation (); }); |
JavaScript-Work notes (event Binding II)