JS basics-event binding and js event binding

Source: Internet
Author: User

JS basics-event binding and js event binding

In the JS event object of the previous blog, the teacher asked how JS event processing is related to event processing in VB? Solve this problem first. Here is an example of event processing in VB.net (I 've been typing JavaScript for a long time and I am not familiar with VB, so I have to review it frequently ):

1. Event Processing VB VS JS
Private Sub button#click (sender As Object, e As EventArgs) Handles Button1.Click MsgBox ("helo! ") MsgBox (sender. width) 'the width MsgBox (sender. name) 'The name Of The event Object that Is triggered Is MsgBox (TypeOf e Is Object)' TRUE MsgBox (TypeOf sender Is Object) 'trueEnd Sub </span>.

Resolution: Look at the above event processing code: we can see that the composition is exactly the same as that in JS, and also includes the event triggering object button1, the event processing function Click and the corresponding function to be executed (which is better understood as the event here) Button1.Click (that is, the action to be executed). It can be seen that their representation is somewhat different.

So there are two parameters sender and e in the event processing. What are their functions?

1. sender: the object that triggers the event. Here, it refers to the button. In the code, the sender is displayed. name to obtain the name of the event object that is triggered, sender. width to obtain the width of the event object that is triggered. Therefore, the sender can be used to obtain information about the event object that is triggered. Type: object

2. e: Do you think e is the same as the input parameter e in event binding in JS? In VB, it is equivalent to an event object that the browser in JS passes to event processing by default. E can be used to obtain relevant event information. In the previous blog, event objects in event processing in JS can also be used to obtain event-related information in VB, for example, the example of modifying a key. In VB, e can also be used to judge the key value pressed by the user, but the syntax is different. It is of the same type as object.

In summary, the event processing in JS is no different from that in VB (I am making a bold guess ...), After understanding the event object, it will be of great help to understand the event binding later.

Bind two JS events

First, let's take a look at event binding: in fact, we are very familiar with event binding here. The delegate used in C # is such an idea. In VB, we also used event binding AddHandler, removeHandler is an application of the event binding idea. The core idea is to mount a method or event to another event or method for execution. The call is like a proxy, by directly calling the same event or method, You can execute all the methods or events (purely prepared sentences) of the same type (or understood as following the same rule) specified ).

Here, the same rule can be understood in the event binding of JS: for example, there is also an object that triggers the event, followed by an event processing function (onClick ), the following describes the specific process of the method to be executed.

For traditional event binding, JS has two common forms: inner and script styles, which can be used to handle simple event functions. For a slightly complex event, this will have a major drawback:

1. You cannot bind multiple functions at the same time.

2. Multiple Functions with the same elements cannot be automatically shielded.

3. this in the function body points to the window instead of the current DOM object.

4. The function execution sequence cannot be executed in the binding sequence.

5. Standardize the event object in the function body

To address the above problems, modern event binding is adopted in JS, but modern event binding addEventListener in W3C can solve the above problems. In IE (attachevent), only the first and 5th cases can be solved. To solve this transfer and standardization event problems in IE, we can use the call value transfer method.

Function addEvent (obj, type, fn) {if (typeof obj. addEventListener! = 'Undefined') {// W3Cobj. addEventListener (type, fn, false);} else if (typeof obj. attachEvent! = 'Undefined') {// IEobj. attachEvent ('on' + type, function () {fn. call (obj, window. event); // uses Object impersonating to solve the this transfer problem, window. the transfer of the event parameter solves the problem of standardized event .});}}

After binding with the above modern events, a problem occurs. Because the call is used for object impersonating, it is difficult to delete unnecessary functions during subsequent encapsulation, the main reason is that you cannot identify the function to be deleted. If you add an ID for each function, you only need to specify the ID to be deleted. To solve this problem, we can add an attribute ID for each event based on the principle that everything in JS is an object for identification. In addition, traditional event binding is used to simulate the binding of modern events to solve the problem of shielding and deleting the same function.

1. Simulate binding of modern events

// Assign a counter addEvent to each event. ID = 1; // to prevent global variable disasters, change the event ID to the property function addEvent (obj, type, fn) {if (typeof obj. addEventListener! = 'Undefined') {// W3Cobj. addEventListener (type, fn, false);} else {// create a hash table for storing events if (! Obj. events) obj. events ={}; // execute if (! Obj. event [type]) {// create an array obj that stores event processing functions. events [type] = []; // store the first event handler function to the first position if (obj ['on' + type]) obj. events [type] [0] = fn;} else {// block the same registration function. if (addEvent. equal (obj. events [type], fn) return false; // if the subsequent function is equal to the first function, it is automatically blocked} // from the second time, the event counter is used to store obj. events [type] [addEvent. ID ++] = fn; // execute the event processing program obj='on'{type={addevent.exe c (); // here we will talk about further encapsulation of the event processing execution function }}

2. encapsulate the execution functions of Event Processing

AddEvent.exe c = function (event) {// here, you need to obtain the event type var e = event through the passed event | addEvent. fixEvent (window. event); // obtain the type var es = this using the event object passed in the addEvent event. events [e. type] // use this to obtain the obj object for (var I in es). {// use this here. events [e. type]. obj cannot be used directly. eventses [I]. call (this, e); // IE needs to pass this to bring up this. value to solve this transfer problem in IE }}

3. Block the same registration function

addEvent.equal=function(es,fn){for(var i in es){if(es[i]==fn) return true;}return false;}

4. Delete events

function removeEvent(obj,type,fn){if(typeof obj.removeEventListener!='undefined'){obj.removeEventListener(type,fn,false);}else {for (var i in obj.events[type]){if(obj.events[type][i]==fn){delete obj.events[type][i];}}}}

It can be seen that in the process of simulating modern events, the event object e plays a great role. It can be used to obtain the type and ID of the added event, it is convenient to delete the object by means of the Properties Obtained by the event object. At the same time, I understand the encapsulation of cross-browser event binding, and it is much easier to understand the JS encapsulation library. During encapsulation, many methods are also implemented on this basis, finally, if you want to implement concatenation, you need to return a core object of the encapsulated library, which is also a core of learning JQuery later.

The above is a personal understanding and does not represent the opinions of Baidu or CSDN. please consider it carefully for your reference!

Js event binding

I wrote it myself. I haven't found any problems after years of use. Please use it for you.
/******************** Object addition event *************** ****/
Function addEvent (obj, type, fun ){
Obj = $ (obj );
If (obj. addEventListener ){
Obj. addEventListener (type, fun );
Return true;
} Else if (obj. attachEvent ){
Return obj. attachEvent ("on" + type, fun );
} Else {
Return false;
/********************* Object deletion event *************** ****/
Function delEvent (obj, type, fun ){
Obj = $ (obj );
If (obj. addEventListener ){
Obj. removeEventListener (type, fun );
Return true;
} Else if (obj. attachEvent ){
Obj. detachEvent ("on" + type, fun );
Return true;
} Else {
Return false;
Forget $ function. Write a simple one.
Function $ (obj ){
If (typeof obj = "object "){
Return obj;
Return document. getElementById (obj );

How to bind events to js

Use attachEvent and addEventListener in IE

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.