Thursday, October 6, 2011

safeCall new and improved.

jQuery Project page

Some other day in the not so distant past, I found a need to have my safeCall plugin also be a safeGet as well. and this task was extremely simple. all the code had been written already for it in the safeCall function. I just had to stop it from calling it at the end and have that be the return. one other thing I noticed jQuery frowned on my attaching my mSafeCall and gSafeCall directly to the jQuery object so instead I created the safe namespace in jQuery so I took off the safe from both of them. and added the gets. and I borrowed a concept that stands at the root of jQuery; the ability to chain.

lets use the following js object for examples it shows just about everything we need it to show:

var TestObj = {
 funcRoute: {
  CallMe: function(msg) { alert(msg); },
  CallMe2: function() { 
   return { 
    NestedCall: function(msg) { 
     alert(msg); 
    },
    NestedGet: "I'm way down here!"
   }
  }
 },
 varRoute: {
  VarA: 5,
  VarB: "Hello world"
 }
};

note: the following four functions return a Safe object. so to get the return value/ value of the get you must call the object returned's value member. More on this later.

$.safe.mCall( Context, FuncPath, [...]);
this function listed above calls a function nested inside a javascript object. Starting from the Context. this is formally $.mSafeCall. the parameters are;

Context: this parameter is the starting point of the path and it is also the "this" for that function.

FuncPath: this parameter is the path to the function. starting from the context that you passed in.

Additional Params:  any additional params that you pass into the function will be passed into the function you are calling.

example: 

$.safe.mCall(TestObj,'funcRoute.CallMe','hi');

the call above will be equivalent to calling TestObj.funcRoute.CallMe('hi') with the exception that the safecall will not break if TestObj, funcRoute, or CallMe haven't been intitialized.


$.safe.gCall( Context, FuncPath, [...]);
this function listed above calls a function nested inside a javascript object. Starting from the window object. this is formally $.gSafeCall. the parameters are;

Context: this parameter is the "this" for that function.

FuncPath: this parameter is the path to the function. starting from the window object.

Additional Params:  any additional params that you pass into the function will be passed into the function you are calling.

example: 

$.safe.gCall(null,'TestObj.funcRoute.CallMe','hi');


Onward to the new functionality.