0

I have a div element in my html code with the class name ".myButton" which holds a data object called

data-action="myFunctionToCall"

HTML

<a href="#" class="myButton" data-action="startPaymentOverAction">Start Over</a>

I also have a jquery document ready object that has my button event inside it.

$(function() {

   function myFunctionToCall( arg ){
    console.log("FUNCTION CALLED");
   }

    $('.myButton').click(function( event ){
        var action = $(this).data('action');
        event.preventDefault();
        if(action){
            document[action](event);

        }
    });
});

The problem is I can only get this function to work if I use eval. documentaction; will not work I get the error "Uncaught TypeError: document.paymentOptionAction is not a function". How can I get around this without using eval.

me-me
  • 5,139
  • 13
  • 50
  • 91
  • http://stackoverflow.com/questions/1723287/calling-a-javascript-function-named-in-a-variable – Chris Nov 11 '15 at 19:31

2 Answers2

0

Your function isn't defined on the document object. You are inside of a function - $(function() {

This simplest way would be:

$(function() {
    var that = this;
    function myFunctionToCall( arg ){
        console.log("FUNCTION CALLED");
    }
    $('.myButton').click(function( event ){
        var action = $(this).data('action');
        event.preventDefault();
        if(action){
            that[action](event);
        }
    });
});
dave
  • 62,300
  • 5
  • 72
  • 93
0

you have to define the function to call, like this:jsfiddle

window.startPaymentOverAction=function(event){
  alert('action data');
}

$(function() {

    $('.myButton').click(function( event ){
        var action = $(this).data('action');
        event.preventDefault();
        if(action){
           window[action]( event );
        }
    });
});
miglio
  • 2,048
  • 10
  • 23
  • But that's making it global. I don;t want it to be global – me-me Nov 11 '15 at 20:22
  • change window by document then. – miglio Nov 11 '15 at 20:32
  • other way is setting the function in an object: [sample](https://jsfiddle.net/mig1098/thtbgjfg/4/) – miglio Nov 11 '15 at 20:43
  • The problem with an object global is I have variables in the document object that the function startPaymentOverActionneeds to get to so it has to stay within that scope. – me-me Nov 11 '15 at 21:40
  • I'm using your sample solution but instead of defining the var Objfn = {} outside the jquery document object i'm doing it inside along with the function. that seems to work. Going to try see if it works when I minify the js files, as eval was break because of the minify process. – me-me Nov 11 '15 at 22:14