Javascript custom events
Events are the most common way to interact with DOM, but they can also be used in non-DOM code-by implementing custom events. the principle of implementing custom events is to create an object for event management. step 1: Create the event object function EventTarget () {this. handlers ={}; // Storage Structure: {event name 1: [func1, func2…], Event name 2: [func1, func2…]……} EventTarget. prototype = {constructor: EventTarget, // Add event addHandler: function (type, handler) {if (typeof this. handlers [type] = "undefined") {this. handlers [type] = [];} this. handlers [type]. push (handler) ;}, // trigger event fire: function (event) {if (! Event.tar get) {event.tar get = this;} if (this. handlers [event. type] instanceof Array) {var handlers = this. handlers [event. type]; for (var I = 0, len = handlers. length; I <len; I ++) {// pass eventto the event handler. event.tar get indicates the object, event. type indicates the event name. You can add the event attribute handlers [I] (event) ;}}, // remove the event removeHandler: function (type, handler) {if (this. handlers [type] instanceof Array) {var handlers = this. handlers [type]; for (var I = 0, len = handlers. length; I <len; I ++) {if (handlers [I] = handler) {break;} handlers. splice (I, 1) ;}}; Step 2: Call the event var eventObj = new (); // instantiate an EventTarget type var handler = function () {alert ('event') ;}; // event handler eventObj. addHandler ('alert ', handler); // Add an event handler 'handler' event to the eventObj object. fire ({type: 'alert '}); // triggers the event handler 'handler' event in the eventObj object. removeHandler ('alert ', handler); // Delete the 'handler' extension in the eventObj object: (event inheritance) we can let other types inherit the attributes of EventTarget and the method definition of the Inheritance Method // the original type inherit var object = function (o) {// F to play a transit role, function F () {} F. prototype = o; return new F () ;}; // subType inherits the prototype var inheritPrototype = function (subType, superType) {var prototype = object (superType. prototype); prototype. constructor = subType; subType. prototype = prototype;} // implement inheritance and extend the property function Person (name, age) {EventTarget. call (this); // inherit the EventTarget attribute this. name = name; this. age = age;} inheritPrototype (Person, EventTarget); // inherits the EventTarget method Person. prototype. say = function (message) {this. fire ({type: 'message', message: message}); // trigger event}; // call // event handler var handMessage = function (event) {alert(event.tar get. name + "says:" + event. message) ;}; var person = new Person ('yhlf', 29); person. addHandler ('message', handMessage); person. say ('Hi there ');