views:

34

answers:

1

I am facing a challenge and don't know how to solve this in jQuery.

My purpose is to write an extended function replacing the Facebook callSWF function.

Facebook callSWF run like that:   **domObj.callSWF("myFunctionName", param1, param2 ... paramx);**

Now, I need to replace that function. For jQuery, I can call the Flash via JS like that:

if($('#swfObj')[0])
 {
  $('#swfObj')[0].myFunctionName(param1, param2 ...);
 }
 else
 {
  $('#swfObj').myFunctionName(param1,param2 ...);
 }

However, that means I have to change for 50+ different places that previous call "callSWF" and replace with this block of code with different function names. that's no good.

so, I decide to write an extension. ideally, i can call like this:

$('#swfObj').callSWF("myFunctionName", param1, param2 ...);

I start writing the function and stuck.... here is my code so far:

(function( $ ){
  $.fn.callSWF = function(swfFuncName, param1) {

 if($(this)[0])
 {
  $(this)[0].**swfFuncName**(param1);
 }
 else
 {
  $(this).**swfFuncName**(param1);
 }

 return this;
  };
})( jQuery );

The part that I don't know how to do is... to dynamicially pass in the function name (which is the swf function name). so, the swfFuncName will be different depending on the flash function that I'm going to communicate with.

e.g i can do that:

**$('#swfObj').callSWF("showMyName", 'whatever');**
**$('#swfObj').callSWF("anotherFunction", 1234);**
**$('#swfObj').callSWF("yetAnotherFunction", 'kbieure');**

any idea? thanks.

+1  A: 

The key is simply to use what most would call "array" syntax instead of "object" syntax to reference the appropriate property of $(this)[0] or $(this) (as the case may be)

 if($(this)[0])
 {
  $(this)[0][swfFuncName](param1);
 }
 else
 {
  $(this)[swfFuncName](param1);
 }
VoteyDisciple
What about if the number of param varies? e.g.some functions may have one, some may have more than one...
seatoskyhk
it works. i just have to figure out a better way to handle multiple parameters. :)
seatoskyhk
to handle multiple params, try: `var elem $(this); = elem[swfFuncName].apply(elem, [param1, param2, param3]);` Read up about [apply](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply)
Anurag