简体   繁体   中英

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!

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 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM