Ben
Ben

Reputation: 10298

JSF + jQuery : AJAX Rendering forces a re-binding to client side (jQuery) events

This is a repeating issue for me and I have a solution but it is a little messy and i'm wondering if there is a better solution or someway to avoid the problem alltogether.

This issue occurs when I bind from jQuery to a DOM component and then re-render that component using JSF/AJAX.

For example:

<h:commandButton>
  <f:ajax render="rerenderedObject" />
</h:commandButton>

<h:panelGroup id="rerenderedObject">
  ...
</h:panelGroup>

And on the jQuery side:

var componentBound = false;
function bindToClick() {
   if (componentBound === false) {
      componentBound = true;
      $('#rerenderedObject').click(function() { 
        // DO SOMETHING 
      });
   }

}

The binding to click is lost whenever the rerenderedObject gets re-rendered (the button is pushed)

I have managed to overcome this by binding to JSF using this code:

$(window).load(function () {
    jsf.ajax.addOnEvent(function(data){
        if (data.status === "success") {
            bindToClick();
        }
    });
});

And yet there exists the problem of multiple event bindings (since not every ajax event re-renders rerenderedObject) hence the componentBound` variable.

This is my solution, I was wondering if anyone had to deal with this and what was your solution.

Thanks!

Upvotes: 1

Views: 1797

Answers (1)

BalusC
BalusC

Reputation: 1109532

Use jQuery.live() instead. It'll put a monitor on newly added elements and reapply the same event handler.

$('#rerenderedObject').live('click', function() { 
    // DO SOMETHING 
});

Upvotes: 1

Related Questions