Search code examples
phpjsonyii

CJSON::encode a javascript function


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?


Solution

  • 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(){}'
    ))