Friday, July 27, 2007

Javascript closure and setTimeout

When we need to pass parameters to function called in setTimeout sometimes we have to use Javascript closure.

Example in function onmouseover we normally call doajax function using this.doajax. In order to achieve a time delay and pass this to doajax we set up a closure using variable callDoajax

<script type="text/javascript" src="prototype.js"></script>
var AJAX_DELAY=2000;
function ALinkObj(elementName, options) {
this.element = document.getElementById(elementName);
if (!this.element) throw new Error(elementName + ' not found');
this.element.alinkobj = this;
this.options = options || {};
this.ajaxboxid = this.options.ajaxboxid || "ajaxbox";

Event.observe(this.element, "mouseover", this.onmouseover.bind(this));
Event.observe(this.element, "mouseout", this.hidebox.bind(this));

ALinkObj.prototype.onmouseover = function() {
this.cursorIn = 'y';

//this.doajax(); //without time delay

//use closure to pass this object
var callDoajax = this.doajax;
setTimeout(callDoajax.bind(this), AJAX_DELAY);


ALinkObj.prototype.doajax = function() {
if (this.cursorIn == 'n') return;
new Ajax.Request(this.element.title,{ method: 'get',
onFailure: displayErr.bind(this) } );

Javascript paper:


Post a Comment

<< Home