-
Notifications
You must be signed in to change notification settings - Fork 36
Description
Currently, one can do
$parameters = new stdClass();
$parameters->foo = 'bar';
$parameters->min = 0;
$parameters->max = 10;
PheryResponse::factory('#elementId')->javascriptFunction($parameters);The PheryResponse::typeCast() function will take care of encoding the provided $parameters object to JSON and hand them over the the client-side. Great!
Limitation
However, when trying to handover JavaScript functions/statements, this approach will (obviously) fail:
$parameters = new stdClass();
$parameters->callbackFunction = 'function() { console.log(this); }'The string 'function() { console.log(this); }' will treated as a normal string and can not be used. This is a known limitation/feature of JSON, also described here:
- http://stackoverflow.com/questions/1745248/php-json-encode-and-javascript-functions
- http://web.archive.org/web/20080828165256/http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/
Workaround
The workaround for now is to use the name of function that is already defined in JavaScript:
$parameters = new stdClass();
$parameters->callbackFunction = 'functionToInvokeAvailableInJavaScript'Possible approach / suggestion
The Zend Framework came up with a way to wrap such statements. in a Zend\Json\Expr object and encode it with a flag to detect such expressions. Maybe this approach can be researched / adopted by Phery. I am not aware of other libraries that provide this functionality.