Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JavaScript this and IE8

 
pawan chopra
Ranch Hand
Posts: 417
jQuery Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65225
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
pawan chopra
Ranch Hand
Posts: 417
jQuery Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65225
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic