jQuery: this and that

Actually, I prefer using self instead of that, but just because I’m more used to program in Python.

The problem actually started when I decided on doing two big changes to my JavaScript code: move from MochiKit to jQuery and change from plain functions in a global scope to namespaced “classes”.

The first part is mostrly straightforward…  Some things change here and there, some rewriting is needed in a few places, but then it is not all that hard after you start to understand the differences between both libraries.

The second part, though, is what prompted me to write this article here.

To make your life easier, jQuery changes the context of the this object according to what triggered the code to run.  It might be an object or it might be a DOM element (another kind of object).

By comment 9 from the above link I found the solution to allow me to use jQuery and keep my object oriented code, using namespaces and factoring out common code.

$('selector').bind('event', {self : namespace}, my_function);

Then, at my JavaScript function, I have:

namespace = {
    my_function: function(evt) {
        var self = evt.data.self;
        // code
    }
};

This allow me to use other functions within the same namespace by referring to this namespace as self.

It took me a while to join the pieces together and the mentioned post helped a lot on creating a clean solution to the problem.

Advertisements

One response to “jQuery: this and that

  1. Pingback: Creating namespaces for your code « Crazy thinking - Just my Weblog

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