PDA

View Full Version : defer attribute of anonymous function



andynuss
7 Jul 2009, 7:22 AM
Hi,

I'm a extjs newbie and having trouble with the following code fragment at the end of "init.js" in the examples folder of the dist.

var hideMask = function () {
Ext.get('loading').remove();
Ext.fly('loading-mask').fadeOut({
remove:true,
callback : firebugWarning
});
}

hideMask.defer(250);

Here we're declaring a function called hideMask, which I would think could only be invoked via "hideMask()". But then we use the "defer" member of hideMask. What is the magic that extjs is doing to make this work, or is it a feature of javascript that I don't know. I just don't see how hideMask acquires the attribute function defer().

Andy

deanna
7 Jul 2009, 8:02 AM
In javascript functions are an object like other objects. The Function object has the defer method that sets a timer, then runs the executable part when the timer fires. Think of a function as an Object with a method that called when javascript language notation uses the () at the end of it, like functionName();

jay@moduscreate.com
7 Jul 2009, 9:05 AM
this is what function.defer is doing

defer : function(millis, obj, args, appendArgs){
var fn = this.createDelegate(obj, args, appendArgs);
if(millis > 0){
return setTimeout(fn, millis);
}
fn();
return 0;
}

mankz
7 Jul 2009, 9:06 AM
...and here's where the magic happens (from ext-core-debug.js) :)



Ext.apply(Function.prototype, {

...

defer : function(millis, obj, args, appendArgs){
var fn = this.createDelegate(obj, args, appendArgs);
if(millis > 0){
return setTimeout(fn, millis);
}
fn();
return 0;
}
});



Edit: Jay, you beat me by < 1 min...

jay@moduscreate.com
7 Jul 2009, 9:11 AM
lol@mankz ;)

btw, this is what createDelegate does


createDelegate : function(obj, args, appendArgs){
var method = this;
return function() {
var callArgs = args || arguments;
if (appendArgs === true){
callArgs = Array.prototype.slice.call(arguments, 0);
callArgs = callArgs.concat(args);
}else if (Ext.isNumber(appendArgs)){
callArgs = Array.prototype.slice.call(arguments, 0);
var applyArgs = [appendArgs, 0].concat(args);
Array.prototype.splice.apply(callArgs, applyArgs);
}
return method.apply(obj || window, callArgs);
};
},






use the force, read the source... it's what the pros do!