0

I need to call a jQuery function with EVAL (but I don't know how to do it), then I solve with this solution, but I don't think that this is the correct way...

<script>
jQuery.fn.customfunction = function (data) { alert( data ); }
</script>

<div id="eval_div"></div>
<form><input role="button" myFunction="customfunction"/></form>
<script>
$('[role=button]').click( function() {
var button = this;
$.post( "/action",
        $(form).serialize(),
        function (data) {
            $('#eval_div').html( "<script>" + $(button).attr('myFunction')  + "('" +  data   + "');</script>" );
        } );
});
</script>

customfunction is a general function for each form, each form has a different CUSTOMFUNCTION with different name, by this reason, the button has the name of the function.

5
  • This code works well.. my question is: Is it the correct way? Commented Sep 17, 2010 at 23:59
  • there is no correct way to use eval Commented Sep 18, 2010 at 0:37
  • @Claudiu - Even Crockford suggests eval() for JSON. Commented Sep 18, 2010 at 3:13
  • @Peter: really? evalling to parse JSON could end up... doing anything. Commented Sep 18, 2010 at 14:52
  • @Claudiu - My bad. Don't know where I got that. At any rate, here's some discussion of eval and JSON and why a parser is better...... user439866 - I realize that. Commented Sep 18, 2010 at 19:06

2 Answers 2

2

If you just want to call the function... you can do it very simply:

function (data) {
    jQuery.fn[$(button).attr('myFunction')](data);
};
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need eval in this case. In JavaScript you can use dot notation or square brackets. They mean the same thing. Try this line.

$('#eval_div').html(jQuery.fn[$(button).attr('myFunction')](data));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.