Search code examples
javascriptfunction

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?


Solution

  • 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.