Javascript's default-global... repressed memories

I used to do ridiculous amounts of Javascript for Holodesk, so I *should* have immediately twigged to this, but it's been 8 years and I've managed to block this particular silliness out.  Say you have a reusable (Dojo) widget where you need to access "this" in a callback.  The callback function will have "this" bound to the widget generating the event, so you do the classic:

that = this;

and go on about your merry way, using "that.whatever" in your callback functions.  You finish your widget and start working on higher-level code, which happens to create a few of your widgets scattered around a page.  But for some weird reason, your widget no longer updates when you click on it.

Puzzled, you try to debug the situation... yes, the events are happening.  Yes, the values are getting set to the correct values... but they don't update on the page.  You spend a bit of time sulking and playing with the silly things... then you notice... there is *one* widget that updates.  What's more, it updates whenever you change *any* instance of your widget.

You shake your head, cry a tear (particularly if you remember just a few weeks earlier defending this particular wart as "dumb, but not enough to throw out the whole language") and alter your declaration to:

var that = this;

Imagining that next time you will remember this immediately, but realizing deep in your heart that something this silly just isn't going to stick in your memory, the beauty-loving part is going to have to block it out if you are to retain your sanity.

Comments

  1. Dougal Matthews

    Dougal Matthews on 12/20/2008 8:11 a.m. #

    I had that same problem recently. I also forget 'new' sometimes after going from Python.

    I recommend your code through http://www.jslint.com/ when you start running into unknown problems, it can save quite a bit of time!

  2. Kevin Dangoor

    Kevin Dangoor on 12/23/2008 8:05 p.m. #

    Dojo has dojo.hitch which is used specifically for dealing with context fun like this...

    I do agree that this is often counter intuitive...

  3. Aaron

    Aaron on 12/27/2008 7:33 p.m. #

    Yep. This is the kind of thing I was talking about at pygta. It's just not a pretty language.

Comments are closed.

Pingbacks

Pingbacks are closed.