How to resolve this point to the bound element when using the attachEvent Function

Source: Internet
Author: User

You can use attachEvent to bind an event multiple times. This is an important way to resolve the event Function Definition conflict. However, in IE, The this pointer in the function does not point to the bound element, but to the function object. In the application, this is very uncomfortable, if you try to use local variables to transfer elements, memory leakage will occur due to closures. So how should we solve this problem?

I added the prototype "bindNode" to the Function. In this method, global storage conversion is performed based on the transmitted elements, and then encapsulated functions are returned, use the call method to convert the owner.



<Html>
<Body>
<Button id = btTest> test </button>
</Body>
</Html>
<Script>
If (! Document. all ){
HTMLElement. prototype. attachEvent = function (sType, foo ){
This. addEventListener (sType. slice (2), foo, false)
}
}
Function. prototype. bindNode = function (oNode ){
Var foo = this, iNodeItem

// Use the Global Array _ bindNodes and use the local variable iNodeItem to pass the value across functions. If the local variable iNodeItem is directly transmitted, it will also cause a closure.
If (window. _ bindNodes = null)
_ BindNodes = []
_ BindNodes. push (oNode)
INodeItem =__ bindNodes. length-1
ONode = null
Return function (e ){
Foo. call (_ bindNodes [iNodeItem], e | event)
}
}
Abc ()
Function abc (){
Var bt = document. getElementById ("btTest ")
Bt. attachEvent ("onclick", function (){

// If bindNode is not processed, the following result will be undefined.
Alert (this. tagName)
}. BindNode (bt ))
Bt = null
}
</Script>

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.