JavaScript implements custom events for custom objects

Source: Internet
Author: User
Tags event listener javascript array

Objective:

As you know, using JavaScript makes it easy to use the AddEventListener function to quickly bind a DOM object to one or more event listeners.

How do we use this method in JavaScript custom objects and trigger events? This is the core of this chapter.


Objective:

Now there is a requirement that the "a object" be able to make a series of actions for the "B object".

After analysis, we learned that. First, the "B object" has a fixed name as a portal for the A object to call, and the portal can automatically retrieve all the functions that meet this action requirement and trigger it sequentially.


Realize:

Well, after the above we can simply understand why we need to customize the event.

Next, let's use the code to implement it specifically.

function Cursomobject (table) {//    <summary> This is a custom object type </summary>//    <param name= "table" Type= "Object" optional= "true" > Function and property sheet to be added </param>/    /here to store our custom event    //Because it is a table, so we use the Object    type This._events = {};    Get the contents of the function and attribute table for    (var i in table) this[i] = Table[i];}

The above code defines a cursomobject type, which will serve as the basis for the operation below.

CursomObject.prototype.addEventListener = function (type, listener, capture) {///    <summary> Add Event listener </ summary>//    <param name= "type" type= "String" > Event type </param>//    <param name= "listener" type = "function" > triggered function </param>    //<param name= "capture" type= "Boolean" optional= "true" > whether it is triggered during the capture phase ( This is just a sequential arrangement) </param>    //Determine if the incoming parameter conforms to the specification    if (typeof type!== "string" | | typeof listener!== "function") Retu RN this;    Cache List of eligible events    var list = This._events[type];    Determine if there is already an event of that type, and if not, add a new array if    (typeof list = = = "undefined") List = (This._events[type] = []);    /* Determine where to insert the function *    /if (!! Capture) List.push (listener);    else List.insert (0, listener);    return this;};
At this point, we have implemented a simple Add function for event listeners.

It is important to note that the Insert function in List.insert does not exist in the JavaScript array, and we will find it in the following extension function.

In addition, return this; For the convenience of chained programming "for details see Appendix 1"

CursomObject.prototype.removeEventListener = function (type, listener, capture) {///    <summary> Remove Event listener </ summary>//    <param name= "type" type= "String" > Event name </param>//    <param name= "listener" type = "function" > triggered function </param>//    <param name= "capture" type= "Boolean" > whether to trigger in capture phase </param>    //Determine if the incoming parameter conforms to the specification    if (typeof type!== "string" | | typeof listener!== "function") return this;    Cache List of eligible events    var list = This._events[type];    If you do not bind such an event, you do not need to handle the    if (typeof list = = = "undefined") return this;    for (var i = 0, len = list.length; i < Len; i++) {        //by looping to determine if there is an event listener function to remove in the event list        if (list[i] = = Listener) {
   //This listener function to remove            list.remove (i) from the event list after it is found;            break;        }    }    return this;};
The above process is simple and clear, a cycle to solve the problem.

It is also important to note that the Remove function does not exist in the array in JavaScript and is also shown in the following extension function.

CursomObject.prot Otype.fireevent = function (Type, E) {//<summary> trigger event </summary>//<param name= "type" type= "Strin G "> Event name </param>//<param name=" E "type=" Object "> Additional Parameter Object </param>//If a function with DOM0 usage is present, this[" O    N "+ type.tolowercase ()] && this[" on "+ Type.tolowercase ()].call (this, e);    Cache List of eligible events var list = This._events[type];    If there is no content in the event list, do not need to handle if (!list | | list.length <= 0) return this;    Block event bubbling switch var isstop = false;    Impersonation Event Object window.event = {stoppropagation:function () {isstop = true;}};    E.stoppropagation = window.event.stopPropagation; for (var i = 0, len = list.length; i < Len; i++) {//all event listeners that exist in the event list through the loop trigger condition//If the function returns false or the eve is called within the event    The Nt.stoppropagation function blocks all subsequent calls to the IF (List[i].call (this, e) = = = False | | isstop) break; } return this;}; 
The comments have been made very clear, and here is no longer a statement of exhaustion.

Then the subject is done. The extension function is released below.

Array.prototype.insert = function (index, value) {//    <summary> Insert Item </summary>//    <param name= " Index "type=" number "> Index </param>//    <param name=" value "type=" Object "> Element </param>//    <returns type= "Array"/>    if (Index > this.length) index = this.length;    if (Index <-this.length) index = 0;    if (Index < 0) index = this.length + index;    for (var i = this.length; i > Index; i--) {        this[i] = this[i-1];    }    This[index] = value;    return this;}; Array.prototype.remove = function (index) {///    <summary> Remove items </summary>//    <param name= " Index "type=" number "> Index </param>/    /<returns type=" Array "/>    if (IsNaN (index) | | index > This.length) return;    This.splice (index, 1);};
OK, it's all done.

The complete code is released below.

function Cursomobject (table) {//<summary> This is a custom object type </summary>//<param name= "table" type= "objec    T "optional=" true "> function and attribute table to be added </param>//here to store our custom event//Because it is a table, so we use the object type this._events = {}; Get the contents of the function and attribute table for (var i in table) this[i] = Table[i];} CursomObject.prototype.addEventListener = function (type, listener, capture) {///<summary> Add Event listener </summary&    Gt <param name= "type" type= "String" > Event type </param>///<param name= "listener" type= "function" > triggered functions and lt;/param>//<param name= "capture" type= "Boolean" optional= "true" > whether to trigger in capture phase (this is just a sequential arrangement) </param>//    Determine if the incoming parameter conforms to the specification if (typeof type!== "string" | | typeof listener!== "function") return;    Cache List of eligible events var list = This._events[type];    Determine if there is already an event of that type, and if not, add a new array if (typeof list = = = "undefined") List = (This._events[type] = []); /* Determine where to insert the function */if (!!    Capture) List.push (listener); else List.insert (0, LisTener); return this;}; CursomObject.prototype.removeEventListener = function (type, listener, capture) {///<summary> Remove Event listener </summa ry>//<param name= "type" type= "String" > Event name </param>//<param name= "Listener" type= "Function" &G t; triggered function </param>///<param name= "capture" type= "Boolean" > whether to trigger in capture phase </param>//Determine if incoming parameters conform to specification I    F (typeof type!== "string" | | typeof listener!== "function") return this;    Cache List of eligible events var list = This._events[type];    If you do not bind such an event, you do not need to handle the IF (typeof list = = = "undefined") return this;  for (var i = 0, len = list.length; i < Len; i++) {//by looping to determine if there is an event listener function to remove in the event list if (list[i] = = listener)            {//Find this listener function to remove list.remove (i) from the event list after it is found;        Break }} return this;}; CursomObject.prototype.fireEvent = function (Type, E) {///<summary> Trigger event </summary>//<param name= " Type "type=" String "> Event name </param>//&LT;param name= "E" type= "Object" > Additional Parameter Object </param>//If there is a function for DOM0 usage, trigger this["on" + type.tolowercase ()] &&amp ;    This["on" + Type.tolowercase ()].call (this, e);    Cache List of eligible events var list = This._events[type];    If there is no content in the event list, do not need to handle if (!list | | list.length <= 0) return this;    Block event bubbling switch var isstop = false;    Impersonation Event Object window.event = {stoppropagation:function () {isstop = true;}};    E.stoppropagation = window.event.stopPropagation; for (var i = 0, len = list.length; i < Len; i++) {//all event listeners that exist in the event list through the loop trigger condition//If the function returns false or the eve is called within the event    The Nt.stoppropagation function blocks all subsequent calls to the IF (List[i].call (this, e) = = = False | | isstop) break; } return this;};  Array.prototype.insert = function (index, value) {//<summary> Insert item </summary>//<param name= "index" Type= "number" > Index </param>//<param name= "value" type= "Object" > Element </param>///<returns type = "Array"/> if (Index > This.length) index = this.length;    if (Index <-this.length) index = 0;    if (Index < 0) index = this.length + index;    for (var i = this.length; i > Index; i--) {this[i] = this[i-1];    } This[index] = value; return this;}; Array.prototype.remove = function (index) {///<summary> Remove items </summary>//<param name= "index" type= "    Number > Index </param>//<returns type= "Array"/> If (IsNaN (index) | | index > THIS.LENGTH) return; This.splice (index, 1);};


Use:

The specific implementation of the custom event is detailed above.

Then we can use it, so how do we use it?

function Test () {    ///<summary> This is a custom type </summary>    //Inheritance property    in Cursomobject Cursomobject.apply (this);} Inherit the function in Cursomobject test.prototype = new Cursomobject ();//define an object derived from the Test type var a = new Test ();// The listener A.addeventlistener that binds a message event ("Message", function (e) {    alert (e);}, false);// A message event is then bound to the listener A.addeventlistener ("message", function (e) {    alert ("content:" + e);}, false);// Trigger Message Event A.fireevent ("message", "This is a parameter ...");

This concludes.

If the question please leave a message, I will reply in time.

Thank you for watching!

JavaScript implements custom events for custom objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.