dojo.hitch


The first time I read about dojo.hitch I didn’t understand anything. I read in a book dojo.hitch is a very important function and widely used into dojo library but I didn’t understand why. I am using my learning of dojo to improve my skill in javascript. I remember the time when I hate javascript. I thought it was a very poor program language and everything I need to do with js was a nightmare. If browser was Netscape one way to to do one thing, if browser was IE other (of a other and a couple of hacks). But the times have changed. XHR and Ajax has reinvented the web. Web pages had became into Web Applications. Asynchronous request had opened our minds to a new generation of web applications, and all of it is thanks to javascript. Each day I spent learning js I see how much I was wrong.

Javascript literals are really powerful but the concept of scope is strange when you come from POO. this.foo in js sounds like $this->foo in PHP but its not the same.

For example in the following example:

dojo.declare("gam.desktop", null, {
    variable1: 1,
    foo: function() {
        dojo.xhrPost({
            url: myUrl,
            load: function(responseObject, ioArgs){
                console.log(this.variable1);
            }),
            handleAs: "json"
        });
    });

console.log(this.variable1); will not display 1 in firebug console. Its strange for me when I started with dojo. The problem is that here this points to the scope of the function foo and not to the scope of class gam.desktop. You can do strange tricky-hacks to solve the problem with global variables or something like that, or use dojo.hitch.

dojo.declare("gam.desktop", null, {
    variable1: 1,
    foo: function() {
        dojo.xhrPost({
            url: myUrl,
            load: dojo.hitch(this, function(responseObject, ioArgs){
                console.log(this.variable1);
            }),
            handleAs: "json"
        }));
    });

elegant isn’t it?

Advertisements

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on March 15, 2009, in dojo, Technology, Web Development and tagged . Bookmark the permalink. 2 Comments.

  1. This helped me a lot!

  2. dojo.hitch vs dojo.connect :: getting the paradigm down will be a sweet day indeed.

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: