Yii CListView - JavaScript issue after pagination update

Yii CListView is a great tool when you want to show a set of data objects as a list in your web app. Everyone will bet the the most helping feature of CListView is the pagination. Simply you don't need to do anything to get pagination work on your list and even more importantly it's AJAX based. Means pages are loaded with AJAX making your application more interactive and user friendly.

So what's wrong with this amazing tool?

If you have HTML elements that needs to be accessed with JavaScript (more specifically jQuery, MooTools, Prototype or any JavaScript library), to attach some events or alter content dynamically when loading, they will work fine for the first page which is loaded in a normal HTTP request and not on the elements loaded with AJAX.

Let's say you want to attach an event to each list item with jQuery.


// the event handler
function clickHandler(evt) {
// do something on click event
}

// assume that each item has the class "item" and id of list container is "itemList"
$('#itemList .item').bind('click', clickHandler);

Now, this would work only when you first load the page and the event handler will not be attached to the items loaded with subsequent pages you load with CListView pagination.
In order to deal with this kind of situations CListView provides a built in solution that we can use to attach our event handler to the items loaded with AJAX too. Simply set the afterAjaxUpdate property of CListView in your Yii view file as below.

// a javascript callback function to run when AJAX update is finish
$afterAjaxUpdate = 'function(id, data) { $("#itemList .item").bind("click", clickHandler); }';

widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'id'=>'itemList',
'afterAjaxUpdate'=>$afterAjaxUpdate
)); ?>

This way you may get even complex JavaScript operations done on your list items, that's up to you. Please do not forget to share your experience here, if possible.

Saranga
Saranga A web developer and highly passionate about research and development of web technologies around PHP, HTML, JavaScript and CSS.
comments powered by Disqus