0

I have a jQuery code:

$('a[name=dialog]').click(function(e) {          
    var param = $(this).attr("name");       
    var param = replaceAll(param,"'","\"");     
    var data = JSON.parse(param);
    $("dialogTitle").text(data.caption);
    $("dialogBody").text(data.bodyText);
 /* here I'm trying to assign event to button*/
   $("#OkButton").click(window[data.myFunc]);   
});
});

in html code:

<ul>
<li><a href="#dialogConfirmation" name="{'caption':'MyCaption', 'bodyText':'BODY TEXT!!!', 'myFunc':'foo'}">link</a></li>
</ul>
<script>
function foo(){
alert('test');
};

My question is how to pass function as parameter via JSON? Is it possible? Does somebody know any other solution? Especial attention on passing function with parameters as parameter. Thank you!

1
  • Looks like you are passing function name correctly as a JSON string, whats the problem? Commented Mar 21, 2012 at 6:38

2 Answers 2

2

As JohnP said, using the data API seems more appropriate. You need to define the function name and params in separate ways, possibly using different data keys.

A stripped down example using the data API:

HTML:

<a href='#' data-fn='foo' data-params='{"john":"doe"}'>link</a>​

JS/jQuery:

// define the function
window.foo = function(params) {
    console.log(params); // the params object
};
$('a').click(function() {

    // grab the function name and params from data
    var fn = $(this).data('fn'),
        params = $(this).data('params');

    // execute
    if ( typeof window[fn] == 'function' ) {
        window[fn](params);
    }
});​

Fiddle: http://jsfiddle.net/jzRPa/

Sign up to request clarification or add additional context in comments.

1 Comment

You offered me using HTML5, but I rewrited it in old school style. Anyway thank you, boys! HTML: <a href='#' name='{"func":"vss","params":"parameter"}'>linker</a> <script> function vss(a){ alert(a+" vss"); } </script> ​jQuery: window.foo = function(params) { alert(params); }; $('a').click(function() { var param = $(this).attr("name"); var data = JSON.parse(param); var fn = data.func, params = data.params; if ( typeof window[fn] == 'function' ) { window[fn](params); } });​
1

It would be better to use the data API of jquery rather than using the name attribute to store your JSON.

You can't pass a function as a parameter in JSON since it's just text, you can however pass the function name and then call it. You just need to make sure window[data.myFunc] is an actual function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.