Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CJSON::encode a javascript function

Tags:

json

php

yii

I use jQuery widget factory (jQuery widgets) for my js widgets.

$.widget('cool.someWidget', {
     options: {
         onSomething: null
     }
     // other js code
});

Normally to run the widget from js you write

$(selector).someWidget({
    onSomething: function() { ..... }
});

In Yii I use CJSON::encode to compile all the initialization properties which include the onSomething event.

echo CJSON::encode(array(
    'onSomething' => 'function() {....}',
));

However due to the conversion (CJSON), it converts the function() {...} to a string so in the document it is written the following

$(selector).someWidget({
    onSomething: "function() { .... }"
});

because the onSomething is actually a string when I call the this._trigger('onSomething') it doesn't run the code.

This problem I have only when I "generate" the view and not with Ajax requests (which I handle differently in the system). Is there some "normal" way of making Yii actually write in the document the function withought the quotes?

like image 924
ptheofan Avatar asked Dec 07 '25 01:12

ptheofan


1 Answers

There is actually a build in way to prevent the encode function from wrapping function declaration with quotes , you should add js: before your function declaration

CJavaScript::enocde(array(
   'prop'=>'value',
   'callback' => 'js:function(){}'
))
like image 200
Nader Avatar answered Dec 08 '25 14:12

Nader