Binding your setTimeout methods in JavaScript using Prototype

Posted on April 20, 2009. Filed under: DHTML, JavaScript | Tags: , , , , |

Never mind, use this instead :-)

www.prototypejs.org/api/function/delay

Two features which are indispensable in Prototype are it’s bind and bindAsEventListener functions. I’m not going to write about what they can do for you, but do know that they are indispensable to OO JavaScript for callbacks, lambda functions, closures etc… One place where I desperately wanted to use bind()ing, as well as have the ability to call methods within an instantiated Class, was with setTimeout() callbacks. Here’s the solution I came up with:


var _Class = Class.create({
    initialize: function() {
        this._someVar = 0;
    },
    function1: function() {
        this._someVar++;
        this.function3();
    },
    function2: function() {
        var _lambda = this.function1.bind(this);
        setTimeout(_lambda,10);
    },
    function3: function() {
        alert(this._someVar);
    }
});

var object = new _Class;
object.function3(); // 0
object.function2(); // 1

Basically, what you do is assign the method you want to call [without the parenthesis ()] to a variable [in this case, _lambda], and finally bind() it…


var _lambda = this.function1.bind(this);

Then, simply assign _lambda to setTimeout().

If you don’t bind() this to the method, it will assume that the this you’re referring to is window, and not your _Class instance.

As always, please comment with any constructive contributions below. I know this isn’t probably the best way to implement this, so if you know a better way, please comment!


Read Full Post | Make a Comment ( None so far )

Recently on Adventures in PHP / DHTML / CSS and MySQL...

Memcache & MySQL PHP Session Handler

Posted on April 8, 2009. Filed under: Memcache, PHP, mysql+ | Tags: , , , , |

Simple Image Resize Calculator Function

Posted on January 8, 2009. Filed under: GD, PHP |

Setting up your localhost as example.com

Posted on June 14, 2008. Filed under: Apache | Tags: , , , , , , , |

Using Memcache with MySQL and PHP

Posted on May 21, 2008. Filed under: Memcache, PHP, mysql+ | Tags: , , , , , |

Use one DB connection on your custom wordpress install

Posted on May 11, 2008. Filed under: PHP, WordPress, mysql+ | Tags: |

Make your website completely UTF-8 friendly

Posted on March 23, 2008. Filed under: PHP, UTF-8, mysql+ | Tags: , , , , |

Never use ORDER BY RAND() again!

Posted on March 5, 2008. Filed under: PHP, mysql+ | Tags: , , , , , |

Installing memcache on Windows for PHP

Posted on January 10, 2008. Filed under: Apache, Memcache, PHP | Tags: , , , , , |

Matching a word / characters outside of html tags

Posted on January 4, 2008. Filed under: PHP, Regular Expressions | Tags: , , , |

Creating Pixelated / Mosaic images with GD in PHP

Posted on January 1, 2008. Filed under: GD, PHP | Tags: , , , , |

Liked it here?
Why not try sites on the blogroll...