That is not possible without thinking of a convention and implementing it yourself.
Say, you have this JSON
'{"title": "Title", "fnCallback": "someCallback" }'
Then you could do, on the client side
function wireupCallbacks(jsonObject) {
if (typeof jsonObject === "object") {
for (var prop in jsonObject) {
var callbackName = jsonObject[prop];
if (/Callback$/.test(prop) && typeof callbackName === "string") {
if (typeof this[callbackName] === "function") {
jsonObject[prop] = this[callbackName];
}
}
}
}
return jsonObject;
}
and call that in the context of an object that provides your callback functions
var someObject = {
someCallback: function() { alert("It works!"); }
}
var jsonObject = {"title": "Title", "fnCallback": "someCallback" };
wireupCallbacks.call(someObject, jsonObject);
jsonObject.fnCallback(); // alerts "It works!"
What's missing:
- currently the function only looks for properties named
"*Callback"
.
- there is no fallback to global functions (these would be properties of the
window
object)
- there is no recursion (nested objects are not visited)
- there is no JSON array handling
Add these features on your own, none of these should be difficult to implement.
someCallback
supposed to be? A constant? Because only constants can be references like that. – Gumbo May 29 '11 at 18:43someCallback
is a callback function. – mc10 May 29 '11 at 18:44