War
War

Reputation: 8628

How can I invoke a function the name of which is stored in a string?

If I have an element on the page like this ...

<span data-function="DoSomething">Click</span>

... and i put this in my page header ...

$(document).ready(function() 
{ 
   $('[data-function]').each(function()
   {
       var fName = $(this).attr('data-function');
       $(this).click(fName);
   });
});

... what goes in place of the comment produce the desired effect of executing the function called "DoSomething".

Note: I no the code above wont work, my question is how to make this work (translate 'DoSomething' in to DoSomething();)

Any ideas guys?

Upvotes: 2

Views: 152

Answers (4)

MrFischer
MrFischer

Reputation: 117

Maybe a little bit clean way:

http://jsfiddle.net/whsPG/

var myfuncs = {
  alert : function() {
        alert("An Alert");
    },
    changeName: function(obj) {
        $(obj).text('Other Text');
    }    
};

$('[data-function]').on('click', function()
{
  value =  $(this).data('function');

   if (myfuncs.hasOwnProperty(value)) {
     myfuncs[value](this);
   }

}); ​

Upvotes: 0

KooiInc
KooiInc

Reputation: 123026

The functions should be available. Try putting them in an Object, like this:

$(document).ready(function() 
{ 
   var fns = {
      DoSomething: function() {/* ... */},
      DoAnotherthing: function() {/* ... */}
   };
   $('[data-function]').each(function()
   {
       var fName = $(this).attr('data-function');
       $(this).click(fns[fName]);
   });
});

Here's a jsfiddle, demonstrating a way to keep everything local to one namespace and assigning handlers based on the data attribute of elements.

Upvotes: 3

Parag Meshram
Parag Meshram

Reputation: 8521

Try calling function with window object -

$(document).ready(function()  {
        $('[data-function]').each(function() {
            var fName = $(this).attr('data-function');

            if (typeof (window[fName]) === "function") {
                $(this).click(window[fName]); 
            }
        });  
}

Upvotes: 2

Jon
Jon

Reputation: 437904

You can use something like

$(this).click(window[fName]);

Where window would be replaced by the appropriate expression if the function DoSomething is not defined in the global scope.

Upvotes: 1

Related Questions