Self encapsulated JavaScript event queue function version

Source: Internet
Author: User
Tags anonymous bind

This article mainly introduces the self encapsulated JavaScript event queue function version, compatible with most browsers, the need for friends can refer to the

Background

There are several minor problems with AddEventListener () or attachevent () binding events in javascript:

An anonymous function added with AddEventListener () or attachevent () cannot be removed.

var obtn = document.getElementById (' btn ');

Obtn.addeventlistener (' click ', function () {
Alert (' button is clicked ')
},false)

Obtn.reomveeventlistener (' click ', function () {
Alert (' button is clicked ')
},false)
The event on the obtn could not be removed because an anonymous function was passed in

In two, IE6-IE8, use attachevent () to bind the reverse execution problem of multiple events.

var obtn = document.getElementById (' btn ');

Obtn.attachevent (' onclick ', function () {
Alert (1)
})

Obtn.attachevent (' onclick ', function () {
Alert (2)
})

Obtn.attachevent (' onclick ', function () {
Alert (3)
})
ie9+ execution Order 1, 2, 3
IE6-IE8 Execution Order 3, 2, 1
Solve the problem

I want to write a Cross-browser event binding module so that it can be reused later and I want to solve the appeal problem. jquery internal use of event queues and data caching mechanism to solve this problem, looked at the relevant source code, it is complex, since a number of methods to try to achieve. Patch code, the original is written with object-oriented, do not want to let people see very complex, all changed into functions to organize.

/* Interface for binding events
*
* @param {Dom-dom} and {type-string} and {fn-function} optional parameters {fnname-string}
* @execute Create an event queue and add it to the DOM object properties.
To join an event handler (function) in an event queue
You can add an identifier for the event handler to delete the specified event handler
*/
function bind (dom,type,fn,fnname) {
Dom.eventqueue = Dom.eventqueue | | {};
Dom.eventqueue[type] = Dom.eventqueue[type] | | {};
Dom.handler = Dom.handler | | {};

if (!fnname) {
var index = queuelength (Dom,type);
dom.eventqueue[type][' Fnqueue ' +index] = fn;
}
else {
Dom.eventqueue[type][fnname] = fn;
};

if (!dom.handler[type]) bindevent (Dom,type);
};

/* Binding Events
*
* @param {Dom-dom} and {type-string}
* @execute bind only one event, handler is used to traverse the event handlers (functions) in the execution event queue
* @caller bind ()
*/
function Bindevent (dom,type) {
Dom.handler[type] = function () {
for (Var guid in Dom.eventqueue[type]) {
Dom.eventqueue[type][guid].call (DOM);
}
};

if (Window.addeventlistener) {
Dom.addeventlistener (Type,dom.handler[type],false);
}
else {
Dom.attachevent (' on ' +type,dom.handler[type]);
};
};

/* Interface for removal of events
 *
 * @param     {dom-dom} and {type-string} optional parameters {fnname-function}
 * @execute   If there is no identifier, execute unbindevent ()
             If there is an identifier, delete the specified event handler, and if the event queue length is 0, execute unbindevent ()
  */
Function UnBind (dom,type,fnname) {
     var hasqueue = Dom.eventqueue && Dom.eventqueue[type];
    if (!hasqueue) return;
    if (!fnname) {
        unbindevent (dom,type)
   }
    else {
        delete Dom.eventqueue[type][fnname];
        if (queuelength (dom,type) = = 0) unbindevent (dom,type);
   };
};

/* Removal Event
*
* @param {Dom-dom} and {type-string}
* @execute Remove the bound event handler handler and empty the event queue
* @caller UnBind ()
*/
function Unbindevent (dom,type) {
if (Window.removeeventlistener) {
Dom.removeeventlistener (Type,dom.handler[type])
}
else {
Dom.detachevent (Type,dom.handler[type])
}

Delete Dom.eventqueue[type];
};

/* Determine event Queue Length
*
* @param {Dom-dom} and {type-string}
* @caller bind () UnBind ()
*/
function Queuelength (dom,type) {
var index = 0;
for (var length in Dom.eventqueue[type]) {
index++;
}
return index;
};

How to use

var obtn = document.getElementById (' btn ');

Binding events
Bind three Click event Functions for button
IE6-IE8 the execution order is unchanged
Bind (OBTN, ' click ', function () {
Alert (1);
})
Bind (OBTN, ' click ', function () {
Alert (2);
}, ' Myfn ')
Bind (OBTN, ' click ', function () {
Alert (3);
})

removing events
Removes all bound click event functions and supports the removal of anonymous functions
UnBind (obtn, ' click ')

Remove only event functions with identifiers as Myfn
UnBind (obtn, ' click ', ' MYFN ')

Program Ideas

The main idea of a program is to add an event queue as a property of a DOM element object to a DOM element without polluting the global environment, which solves the problem of data storage for multiple event functions that are bound by different DOM elements to different event types.

Event queues on DOM elements
dom{
EventQueue: {
' Click ': {
Fnqueue1:function,
Myfn:function,
Fnqueue3:function
}

' MouseOver ': {
Fnqueue1:function,
Fnqueue2:function
}
}
}

Each time the event function is added to the event queue of the corresponding event type, only one event is bound. When an event is triggered, the handler event function is executed, and handler iterates through the event functions in the execution event queue.

UnBind () If there is no incoming identifier, remove all bound event functions, support the removal of anonymous functions, or remove the specified event function if there is an identifier. Program logic is not complex, there may be bugs and performance problems, interested can guide the exchange under the

Related Article

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.