JS Basics-Event Binding

Source: Internet
Author: User

On a blog JS event object, the teacher asked the JS event processing and VB Event processing what is the connection? First to solve this problem. To give an example of VB.net event processing (JS knock Long, VB habits are unfamiliar, it seems to often review):

1, Event processing VB VS JS
Private Sub button1_click (sender as Object, e as EventArgs) Handles Button1.Click        MsgBox ("helo!")        MsgBox (sender.width) ' pop-up triggers this event object's width        MsgBox (sender.name) ' Popup triggers the name of this event object        MsgBox (TypeOf E is Object) ' TRUE        MsgBox (TypeOf sender is Object) ' TrueEnd Sub</span>

Parsing: Look at the event handling code above: You can see that the composition and JS are identical, including the object that triggered the event button1, the event handler click and the corresponding function to execute (this is understood as the event better) Button1.Click (that is, the behavior to be performed), it can be seen that their representation is somewhat different.

So there are two parameters in this event handler, sender and E, what do they do?

1. Sender: The object that triggered the event, this is the button, By ejecting Sender.name in code to get the name of the event object being triggered, sender.width to get the width of the event object being triggered, and so on, it is visible that sender can get the information that triggered the event object. Type is Object

2, E: here to see if E and JS in the event binding in the parameter E is a bit like it? In VB it is equivalent to the browser by default in JS passed to the event processing of an event object. Through e can obtain relevant information related to the event, also in the previous blog through the event object in JS to get some information about events in VB can also be done, such as the modification of the key example, in VB through E can also be used to judge the user pressed the key value, but the syntax is different. Likewise its type is Object

In summary, JS in the event processing and VB in no difference (personal bold guess in ...) ), it is helpful to understand the event bindings later when you understand the event object.

Two JS event bindings

First understand the event binding: In fact, here is the event binding, or is very familiar with, C # in the use of the delegation is such a thought, VB also used in the event binding Addhandler,removehandler is an application of the idea of event binding. The core idea is that one method or event is attached to another event or method to execute, and the invocation is like an agent that invokes the same event or method directly to perform all the methods or events (purely personal fabrications) of the same type (or understood to follow the same rule).

Here the same rule in the JS event binding can be understood as: for example, there is also a trigger event object, followed by an event handler (OnClick), followed by the method to execute the specific process, and so on.

For traditional event bindings, there are two common forms of JS, inline and script styles, which can often be used to handle simple event functions, which are a little more complex to have a lot of drawbacks:

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

2. Multiple identical functions on a unified element, not able to automatically mask the same function

3. This in the function body points to the window, not the current DOM object

4. The order of function execution cannot be executed in the binding order

5. Need to standardize the event object in the function body

In view of the above problems, JS in the modern event binding, but in the Internet, the direct adoption of modern event binding AddEventListener can solve the above problems, ie (attachevent) can only solve the first and 5th. In order to solve this transfer and standardization event problem in IE, we can use call value method to solve it.

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) ;//using object impersonation to solve this pass problem, the window.event parameter is passed to solve the problem of standardizing event. });}}

After the above modern event binding, there is a problem, because the use of call to impersonate the object, resulting in the subsequent encapsulation, the removal of unnecessary functions when the difficulty, the main reason is not to identify exactly which function to delete, if you add an ID for each function, delete, as long as the ID to be deleted is indicated. To solve this problem, we can add an attribute ID to each event to identify it, based on the principle of all JS objects. At the same time, in view of the remaining problems in IE, traditional event binding is adopted to simulate the way of modern event binding to solve the problem of the same function masking and deleting the specified function.

1. Simulate modern event bindings

Assign a counter addevent.id=1 to each event; To prevent global variables from being catastrophic, change the event ID to addevent property function Addevent (OBJ,TYPE,FN) {if (typeof obj.addeventlistener!= ' undefined ') {// W3cobj.addeventlistener (Type,fn,false);} else {//create a hash table that holds the event if (!obj.events) obj.events={};//executes the first execution if (!obj.event[type]) {//creates an array holding the event handler function obj.events[ type]=[];//The first event handler function to first position if (obj[' on ' +type]) obj.events[type][0]=fn;} else {//the same registration function is masked, not added to the counter if (Addevent.equal (OBJ.EVENTS[TYPE],FN)) return false;//If the following function is equal to the first one, the auto-mask}//starts from the second time, Use event counters to store obj.events[type][addevent.id++]=fn;//execution event handlers obj[' on ' +type]=addevent.exec (); Here the event handling execution function is further encapsulated}}

2. Package Event Handling Execution function

Addevent.exec=function (event) {  //Here you need to get the event type by passing events var e=event| | Addevent.fixevent (window.event); Get type var by the event object passed in addevent events Es=this.events[e.type]//replace obj with this to get obj object for (var i in  es) {// Here to use This.events[e.type], can not directly use Obj.eventses[i].call (this,e);  IE needs to pass this to eject This.value value, resolve this pass problem in IE}}

3, the same registration function to block

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 simulation of modern events, ie, the event object E has a great effect, through which can get the type and ID of the added event, and at the time of deletion, it is convenient to delete it by the property obtained by the event object. At the same time, understand the cross-browser event binding package, the following JS Packaging Library understanding is a lot simpler, encapsulation, many methods are also on this basis to carry out, and finally if you want to implement concatenating, need to return to a core object of the package library, which is also a core of learning jquery behind.

The above is purely personal understanding, does not represent Baidu or csdn opinion, if the reference, please carefully consider!





JS Basics-Event Binding

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.