3

i am trying to call a function which is defined in another js file by afterAjaxUpdate paramter of the file name but i got error in console that function is not defined

<?php 
$dataProvider=new CActiveDataProvider('profiles',array('pagination'=>array('pageSize'=>3))); ?>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_profilesview',
'template'=>'{sorter}<br />{pager}{items}{pager}',
    'enableSorting' => true,
    'sortableAttributes'=>array(
     'name'=>'By firstName',
     'location'=>'By city',
     'age'=>'By age',
     'likes'=>'By likes'
     ),
     'afterAjaxUpdate'=>'readcookie()',
));
 ?>

my js function is

$(document).ready(function(){
   function readcookie()
   {
       alert("hi");
   }
});

i can see in my source that function defined in the file is included after all the js files that are included by yii default when i register my script in my layout it dosent find $ because jquery not included when i include jquery it gets included twice which leads to trigger my event i also tried to by setting

renderPartial('Mybelowview',null,false,true)

which leads again my js file to include multiple times and my event gots trigger multiple time.

This is very confusing please help to get out of it Thanks all for being so generous

Bipin Chandra Tripathi
  • 2,550
  • 4
  • 28
  • 45
  • you have included the js file with the `readcookie()` function in the layout or view? – bool.dev Jun 11 '12 at 06:22
  • yes. but when i view source of the HTML page found that it is called after all the yii included JS file so i got error function undefined – Bipin Chandra Tripathi Jun 11 '12 at 06:30
  • @bool.dev now what i did, instead of calling the function i defined it there but i dont feel its a good way since i will have to define it every time i will use it anywhere else can u suggest me right way doing this – Bipin Chandra Tripathi Jun 11 '12 at 06:31
  • show me the code of how you were doing it before, so that i can recreate it here and see what could have been wrong, how you were registering, and in which file/view/layout – bool.dev Jun 11 '12 at 06:42
  • here is my code http://pastebin.com/embed_js.php?i=BiihjQxe thanks a lot. – Bipin Chandra Tripathi Jun 11 '12 at 06:52

1 Answers1

3

The problem is that functions inside $(document).ready(); are out of scope outside of it, and that's why you get undefined. So you can either just have:

// $(document).ready(function(){
   function readcookie()
   {
       alert("hi");
   }
// });
// omit document.ready to make function available in the global scope

or define the function on the window object to make it global:

$(document).ready(function(){
   window.readcookie=function ()
   {
       alert("hi");
   };
});

Lastly define the attribute 'afterAjaxUpdate' as :

'afterAjaxUpdate'=>'readcookie'
// if it is readcookie() it becomes a function call instead
bool.dev
  • 17,508
  • 5
  • 69
  • 93