开发者

JQuery: how to write a plugin function that will take a function name as string and run it?

I a开发者_JAVA百科m 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.


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);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜