Two Laptop Bag*
The moose likes HTML, CSS and JavaScript and the fly likes JavaScript this and IE8 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "JavaScript this and IE8" Watch "JavaScript this and IE8" New topic
Author

JavaScript this and IE8

pawan chopra
Ranch Hand

Joined: Jan 23, 2008
Posts: 413

Hi,

I am trying to do some experiments in JavaScript. You can have a look at the code here:

http://jsfiddle.net/2mbTF/2/

I am trying to extend DOM api. It may not be a good idea. But just for my own knowledge I have a question. This code doesn't work on IE 8.

"this" variable in add method should be div element. But in IE8 it's Window object. Can anybody clarify if I am doing anything wrong here.


Pawan Chopra
SCJP - DuMmIeS mInD
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61766
    
  67

Assuming that you know what the function context (this) is in an event handler is tricky business.

You can use jQuery event handling (highly recommended) which takes care of it for you, or learn to use closures to bind the function context to always be what you want. The latter is what jQuery's proxy() method does (as well as Prototype's bind()).

If you want a detailed explanation, I go over it in depth in chapter 5 of Secrets of the JavaScript Ninja.

Essentially, you wrap the handling function in another, that calls the handler with a function context of your choosing, and establish the wrapper function as the event handler. Give the code a try and see if you can get it to work.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
pawan chopra
Ranch Hand

Joined: Jan 23, 2008
Posts: 413

Yes, I was able to do that using Closures. I am currently trying few things in JavaScript just for learning. So that was the reason I was trying this. But things are really weird when you go to IE8. Things like cloneNode. If I clone a node B from node A. I read in documentation that cloneNode will not copy events. But in case of IE one weird thing is going on. I have click event on node A. Now when I call cloneNode and create new node B. That should not have any click event. But when I click on node B. It fires click event on Node A. I think it's completely unexpected. I understand now why building a library like jQuery was a big job. Thanks for your help.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61766
    
  67

Yeah, cross-browser JavaScript -- especially with older versions of IE (and to some extent even modern IE) -- is not for the faint of heart! Thanks goodness for libraries such as jQuery that level the playing field and have solved most of the knottier problems for us!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JavaScript this and IE8