Passing a callback function in options object to other function

228 views Asked by At

I am surely doing it wrong and now I am stuck. What I want to do is to pass function as callback to another function.

My function:

function myfunc(options, callback) {
 var settings = {
  opt1 = "something",
  url = "someURL"
 }
 if( options ){
  $.extend( settings, options );
 }
 $.ajax({ 
  url: settings.url,
  success: function(data) {
   callback();
  }
 });
}

And the HTML that delivers parameters:

<input type="button" id="btn" value="Click me" data-callback="callbackFN" />

The click event:

$("#btn").click(function() {
 myfunc({
  opt1: "text",
  url: "theURL"
 }, $(this).data("callback"));
});

Unfortunately the callback always is passed as a plain string and not as a callable function. I know it sounds like a newbie question but I am stuck on this. Please help.

1

There are 1 answers

0
apsillers On BEST ANSWER

$(this).data("callback") returns a string. You want to find the actual function identified by the string returned by $(this).data("callback").

If the function is global, you can do window[$(this).data("callback")] to refer to window.callbackFN.

If the function is not global (i.e., it is local to a function), you may be able to refer to it using eval, but this could open large security issues in your code. For example, consider data-callback="alert(document.cookie)".

If you wish to avoid both global callbacks and eval, another option could be to place your callbacks inside an object instead of the global scope:

var myCallbacks = {
    callbackFN: function() { ... },
    otherCallback: function() { ... }
}

Refer to them with myCallbacks[$(this).data("callback")].