Custom event work notes in JavaScript

Source: Internet
Author: User
Tags event listener

What is a custom event

Custom events are always around, but we may use them very little, and we can look at the usage of jquery:

The code is as follows Copy Code
Listening for custom events
$node. On (Custom_event_name, CALLBACKFN);
Triggering custom Events
$node. Trigger (Custom_event_name, params);
To unbind a custom event
$node. Off (Custom_event_name, FN);

See here, we will find that this is the same as we used to the browser event usage is almost the same, but a more trigger method.
So how do we understand custom events?

Realize

Let's take a look at the implementation of the real custom event, which makes it easy to understand the custom event.
First of all, there is an event object, we call events = {};

Event Monitoring

Each event is monitored (or registered), such as $node.on (Evt_name, EVTFN), which corresponds to a deal with the event object: events[evt_name] = [EVTFN];
The equivalent is to add a key value to the event object and a corresponding array object that holds the callback function.

Event lifted

The custom event is actually done in the opposite way to the event listener. You increase my deletion.

Event triggers

Finally, the event triggers.
Event triggering is equivalent to executing the array object of the stored callback function sequentially.

Implementation code

Through the event mechanism, the class can be designed as an independent module, and the development efficiency of the program is improved by the external communication of events. ”。 believe that C # programmers are deeply aware of the benefits of events. Well, the code is cheap. Look at the codes:

The code is as follows Copy Code
function Class1 () {//simplest event design pattern
}
Class1.prototype = {
Show:function () {
this. OnShow ();
},
Onshow:function () {}
}
function Test () {
var obj = new Class1 ();
Obj.onshow = function () {
Alert ("Test");
}
Obj.show ();
}

Let's see how to pass parameters to an event handler:

The code is as follows Copy Code
//encapsulate functions with parameters as parameterless functions
function createfunction (obj, strfunc) {
var args = [];//define args to store parameters passed to event handlers
if (! obj) obj = window; Fruit is a global function, then Obj=window;
//Gets the arguments passed to the event handler
for (var i = 2; I < arguments.length i + +) Args.push (Arguments[i]);
//To encapsulate an event handler call with a parameterless function
return function () {
obj[strfunc].apply (obj, args);//pass parameters to the specified event handler
}
br> function Class1 () {
}
Class1.prototype = {
Show:function () {
this. onshow ();
},
Onshow:function () {}
}
function Objonshow (userName) {
alert ("Hello," + userName);
}
Function Test () {
var obj = new Class1 ();
var userName = "Test";
Obj.onshow = createfunction (null, "Objonshow", userName);
Obj.show ();
}

"Because the event mechanism only passes the name of a function, without any parameters of the information, so can not pass parameters into the", this is something, "to solve this problem, can be considered in the opposite way, regardless of how to pass the parameters, but consider how to build a parameter-free event handler, The program is created from an event handler with parameters and is an outer encapsulation. "The program" here is the Createfunction function, which skillfully encapsulates a function with parameters as a parameterless function using the Apply function. Finally, let's look at how to implement multiple bindings for custom events:

The code is as follows Copy Code
Enable custom events to support multiple bindings
To encapsulate a function with parameters as a function without parameters
function createfunction (obj, Strfunc) {
var args = []; Defines args used to store parameters passed to an event handler
if (! obj) obj = window; If the global function is Obj=window;
Get the arguments passed to the event handler
for (var i = 2; I < arguments.length i + +) Args.push (Arguments[i]);
To encapsulate the invocation of an event handler with a parameter-free function
return function () {
Obj[strfunc].apply (obj, args); Passing parameters to the specified event handler
}
}
function Class1 () {
}
Class1.prototype = {
Show:function () {
if (this. onshow) {
for (var i = 0, i < this. Onshow.length i + +) {
this. Onshow[i] ();
}
}
},
Attachonshow:function (_ehandler) {
if (! this. onshow) {this. onshow = [];}
this. Onshow.push (_ehandler);
}
}
function Objonshow (userName) {
Alert ("Hello," + userName);
}
function ObjOnShow2 (testname) {
Alert ("Show:" + testname);
}
function Test () {
var obj = new Class1 ();
var userName = "Your name";
Obj.attachonshow (Createfunction (null, "Objonshow", UserName));
Obj.attachonshow (Createfunction (null, "ObjOnShow2", "test Message"));
Obj.show ();
}

We see that the basic idea of the Attachonshow method is the push operation of the array, in fact, we can remove the event handler function after the event is finished, and implement the following separately:

The code is as follows Copy Code
var event = document.createevent (type);

Type: Can be a htmlevents in DOM level 2 or a mouseevent in DOM level 3
Refer to Https://developer.mozilla.org/en/DOM/document.createEvent

2 Initialization of events

Event.initevent (Type, bubbles, cancelable);
Type: Name of the custom event
Bubbles: Bubble or not
Cancelable: Do you want to cancel

3) Listening for events

Target.addeventlistener (type, listener, usecapture);
Type: The name of the event registered when initializing
Listener: The function that is normally triggered for an event to be executed
Usecapture Indicates whether the event is executing in bubbling or capturing phase

Refer to Https://developer.mozilla.org/en/DOM/element.addEventListener

4) Distribution of events

The code is as follows Copy Code

BOOL = Element.dispatchevent (event);
Manually distribute this event to trigger the listener function in 3

A complete example:

Create the event
var evt = document.createevent (' Event ');
Define the event name is ' Build '
Evt.initevent (' Build ', true, true);

Elem is any element
Elem.dispatchevent (EVT);



Later on.. Binding to that event
We ll bind to the document for the event delegation style.
Document.addeventlistener (' Build ', function (e) {
E.target matches the elem from above
}, False);

There is also a use of custom event simulation click

The code is as follows Copy Code

//Encapsulate functions with parameters as parameterless functions
function createfunction (obj, strfunc) {
var args = [];//define args to store parameters passed to event handlers
if (! obj) obj = window; If the global function is Obj=window;
//Gets the arguments passed to the event handler
for (var i = 2; I < arguments.length i + +) Args.push (Arguments[i]);
//To encapsulate an event handler call with a parameterless function
return function () {
obj[strfunc].apply (obj, args);//pass parameters to the specified event handler
}
br> function Class1 () {
}
Class1.prototype = {
Show:function () {
if (this. onshow) {
for (var i = 0; I < this. Onshow.length; i + +) {
this. onshow[i] ();
}
}
},
Attachonshow:function (_ehandler) {//attached event
if (! this. onshow) {this. onshow = []; br> this. Onshow.push (_ehandler);
},
Detachonshow:function (_ehandler) {//Remove event
if (! this. onshow) {this. onshow = [];}
this. Onshow.pop (_ehandler);
}
}

function Objonshow (userName) {
Alert ("Hello," + userName);
}
function ObjOnShow2 (testname) {
Alert ("Show:" + testname);
}
function Test () {
var obj = new Class1 ();
var userName = "Your name";
Obj.attachonshow (Createfunction (null, "Objonshow", UserName));
Obj.attachonshow (Createfunction (null, "ObjOnShow2", "test Message"));
Obj.show ();
Obj.detachonshow (Createfunction (null, "Objonshow", UserName));
Obj.show (); Remove one, show the remaining one
Obj.detachonshow (Createfunction (null, "ObjOnShow2", "test Message"));
Obj.show (); Two are removed, one is not displayed
}

1) Creating Events

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.