get and performing function + parameters from HTML5 data- element with jquery

Go To StackoverFlow.com

0

I am making a phonegap program and I want to use a .on('tap') event instead of onClick="blah(param1,param2)" because of the 400ms delay. What I wanted to do was give a list of "tappable" items a class of "button1" and with each item give it a data-meth="dosomething3()" and then retrieve that when something is tapped. So far my example does not use tap but click instead.

       <script>
    $(document).ready(function() {
    console.log('document ready');
    $(".button1").on('click', function(e){ //this will changed to 'tap' eventually
    e.preventDefault();
    console.log("logged click");
    var tempp=$(this).data("meth");
    alert(tempp);
    tempp; // thought this would call the function as it is written in the data-meth value but it doesn't
    });

    });
    function dosomething(){
    console.log('dosomething called');

    }
function dosomething(var1,var2){
alert('hello:' +var1+' just showing var2'+var2);
}

    </script>

My simple html is 

    <ul>
    <li style="text-align:center" class="button1" data-meth="dosomething()" >One</li>
    <li style="text-align:center"  class="button1" data-meth="dosomething2(var1,var2)">Two</li>
    <li style="text-align:center" class="button1" data-meth="dosomething3()">Three</li>
    </ul>

How can i grab and call the function based or what is stored in the data-meth value?

2012-04-05 17:14
by CI_Guy


0

Off the top of my head:

$(".button1").click(function() {
    var functionName = $(this).attr("data-meth").split("(")[0];
    var functionParams = $(this).attr("data-meth").split(")")[0].split[","];
    window[functionName](functionParams);
});​

functionParams would be an array containing your values. That may or may not be what you need. You could also use the ever-evil eval like so:

$(".button1").click(function() {
    eval($(this).attr("data-meth"));
});​

In which case you could pass in your parameters and treat them as usual.

2012-04-05 17:20
by Elliot Bonneville
eval(); worked for me as intended , thanks! - CI_Guy 2012-04-05 17:25
No problem, just be careful how you use eval(). Google its shortcomings before you use it again. It's probably okay in this case, though - Elliot Bonneville 2012-04-05 17:27
I am using with phonegap for an android app so not like it is going to be a normal internet site - CI_Guy 2012-04-05 17:31
Ah, okay, cool. Phonegap is awesome. : - Elliot Bonneville 2012-04-05 17:32
Ads