JS code stops working, when published with CClientScript?

As most of my problems, this is probably obvious! :] But I decided to ask, as I can’t find answer myself since yesterday.

This is a piece of my JS code, that I publish to page (view) contents directly like this:


echo('<script type="text/javascript">'."\n");


echo("

    	function configTreeClickHandler(nodeNumId)

    	{

            	$('.".$this->_dummyClass."').hide();

            	$('#' + nodeNumId + '-config-section').show();


            	return false;

    	}


    	var idsArray = ".CJavaScript::encode($this->_idsArray).";


    	configTreeClickHandler(idsArray[".$startID."]);

");


echo('</script>'."\n");

It works fine, but - as supposed - it is being published exactly, where I publish it - i.e. inside view contents.

When I’m trying to publish exactly the same piece of code with CClientScript:


Yii::app()->clientScript->registerScript('ctch',

"

    	function configTreeClickHandler(nodeNumId)

    	{

            	$('.".$this->_dummyClass."').hide();

            	$('#' + nodeNumId + '-config-section').show();


            	return false;

    	}


    	var idsArray = ".CJavaScript::encode($this->_idsArray).";


    	configTreeClickHandler(idsArray[".$startID."]);

");

it fails! Click handler is not being found (although code exists, only this time it is published in the bottom of page, along with other JS codes published with CClientScript) and clicking on items that has this handler attached in onClick ends with console message saying: "[b]Error: configTreeClickHandler is not defined

File: myaapp/admin/config.html Line: 1[/b]".

Got no idea, what is going on. Why browser can’t find code, if it really is inside page source? I thought that there is no different between publishing code with CClientScript and directly with echo().

Hey Trejder

The difference is where it publishes the code

Try to set a different position for it in the head (3rd parameters CClientScript::POS_HEAD) and see what happens

It will work

Gustavo,

Thanks (+1). I’m devastated - because the only reason, why I didn’t test it with POS_HEAD was that, I was pretty sure that I many of my scripts (similar to this) were working, not matter if JS code is in head, body or in the end of page.

Had to do some tweaks (like function calling line had to be moved to the end of file), but it works - and this is most important - thanks again! :]

I had this same problem once and took me a long time to figure it out …

Its weird because the ‘onclick’ event occurs after the function is loaded

In case you dont know, for performance reasons ( the content is displayed and after the JS is loaded ) its better to use in the POS_END, or at least POS_READY

In your case, POS_READY should do the job with better performance

Anyway, glad I could help Trejder( thanks for the plus 1 :D )