I am trying to implement jQCloud word cloud with click event handler. It requires me to pass a javascript function in JSON.
In C#, I have made the dynamic JSON text
foreach (var r in result)
{
sbChart.Append("{\"text\": \"" + r.Key + "\", \"weight\": " + r.Count().ToString() + ", ");
sbChart.Append("\"handlers\": { \"click\": \"function() { alert('You clicked " + r.Key + "');}\"}}, ");
}
if (sbChart.Length != 0)
{
returnString = "[" + sbChart.ToString().Substring(0, sbChart.Length - 2) + "]";
}
I return this through web method to javascript where my code is
var words = JSON.parse(strJSON);
$('#div').jQCloud(words);
The JSON generated is
[
{"text": "the", "weight": 111, "handlers": { "click": "function() { alert('You clicked the');}"}},
{"text": "in", "weight": 66, "handlers": { "click": "function() { alert('You clicked in');}"}}
]
However, since my function is a string, it does not gets execute as a object. And if I remove the double quotes before and after the function statement, it gives me Invalid Character error during parse.
Please can anyone help me as to how can I make this alert work?
If you absolutely have to pass a function to your page that way (see the "but" below), you could use eval for it, since you're the one providing the text you'll be evaling it doesn't have the security issue (and the speed issue is a non-issue and has been for years). I'm not sure what you want to do with the function, but for instance:
$(".foo").on("click", eval(words[0].handlers.click));
...would eval the function and assign the result as a click handler on the elements matching the .foo selector.
But, there's almost certainly a better way to structure things. Instead of passing back functions in the JSON, you might have those functions in your JavaScript already in some kind of map:
var clickHandlers = {
"the": function() { alert("You clicked the"); },
"in": function() { alert("You clicked the"); }
};
...and then just given the key ("the", "in") in your JSON.
Or, given that they're the same thing other than what was clicked, figure out what was clicked ("the" or "in") from the element that was clicked.
Or any of a dozen other things, but what they have in common is that the functions are defined in your JavaScript code, not sent back via JSON, and then you link up those functions via information in the JSON rather than actual functions in the JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With