chenb•log

I don’t mind if I’m incomprehensible

JavaScript Late Binding?

with one comment

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.

Advertisements

Written by Barry

October 10, 2007 at 12:40 pm

Posted in Nerdy

One Response

Subscribe to comments with RSS.

  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.

    Daniel

    December 22, 2007 at 3:35 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: