Wednesday, July 20, 2011

SafeCall JQuery

Often times when  programming in Javascript, you need to check to see if a function exists before calling it. so for instance if you are a programmer you might need to use sys.application.add_load(handler)

so if you were checking if that function esists you would need to do the following.

if(sys && sys.Application && typeof(sys.Application.add_load) == 'function')

What this little snippet of code does is simplify that into:


what this function does is check if the function that is passed in is in fact a function and calls it passing in parameters from it's self to the function. it will start looking for the function Starting from window. (thus being the global calling)
the signature for this function is:

$.gSafeCall(context,handler [...] );

where the following parameters are:

context: the js object that represents this. so when you call the function and context is an object in the function this will be the object you passed in.

handler: this is a string that represents the path to the object starting from the window. the function will try to transverse to the function in question.

params: these are the optional parameters that should get passed into the function.that you are calling.

there also is a function called mSafeCall wich does the same thing but instead of starting from window it will start from the context and locate the function from the context that gets passed in. More on this in the code to follow