JavaScript Late Binding?

— Barry on October 10, 2007 at 12:40 pm

This is my first nerdy post. It is about JavaScript.

Some of you stopped reading at “JavaScript” yes? Good.

Lets say I have a side bar with an edge that when clicked toggles the side bar. I want to represent this side bar as an object with the methods of show and hide. So I might have code that looks like this:

Sidebar = new function() {
    var edge = $('#sidebar_edge');
    this.show = function() {
        /* do some stuff to the UI blah blah blah I hate IE >.< */
        edge.unbind('click');
        edge.click(this.hide);
    }
    this.hide = function() {
        /* la-di-da! la-di-da! */
        edge.unbind('click');
        edge.click(this.show);
    }
}();


(The code assumes that you are using jQuery, because I am and you should.)

Now, that doesn’t work. When I bind this.hide to the click event on the last line of this.show, this.hide has not been defined. But if I change this.hide to Sidebar.hide, then it’d work just fine.

If any JavaScript gurus are reading this, please explain why that is (without telling me to read the ECMAScript specification :-P).

EDIT: Meh. I just realized that it’s probably a scope thing.

1 Comment »

  1. The ‘this’-reference inside your show()-function will be a reference to the DOM-element that caused the click event, not the Sidebar instance (as you assumed).
    Your first assumption about the hide() function having to be declared before the show() function is wrong.
    For example you could save a reference to the Sidebar instance as an Attribute of the DOM-element (elem.MySidebar = this) and then refer to it via this.MySidebar in the click-Event-Handler.

    Comment by Daniel — December 22, 2007 @ 3:35 am

RSS feed for comments on this post.

Leave a comment

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. | chenb•log