2

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?

War
  • 8,539
  • 4
  • 46
  • 98

4 Answers4

3

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.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • I love this, it pushes the JS in to a more object oriented model instead of the typical "quick and dirty solution" i'm finding myself implementing a lot (dispirate functions with no relationships unlike something like C# on the server which forces you to group your functions in to classes giving your code structure) – War Aug 21 '12 at 11:36
  • @Wardy, yep, that's the idea. – KooiInc Aug 22 '12 at 06:45
2

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]); 
            }
        });  
}
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88
1

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • probably a stupid question but ... what is the "appropriate expression" / how is it determined? – War Aug 21 '12 at 11:35
  • @Wardy: "It depends" (on your code). If you define it as a global function it's `window`. Or it could be something like Kooilnc's example. – Jon Aug 21 '12 at 11:38
0

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

}); ​

MrFischer
  • 117
  • 1
  • 4