开发者

h:commandLink not firing the form.submit event

开发者 https://www.devze.com 2023-04-09 05:35 出处:网络
When my page is loaded I execute the following JS script, which I use to display a popup saying (please wait...) when any form is submitted.

When my page is loaded I execute the following JS script, which I use to display a popup saying (please wait...) when any form is submitted.

jQuery(function(){
  jQuery("form").submit(function(){jQuery('#wait-link').trigger('click');return true;});
});

This works fine when using h:commandButton tag, however when I use the h:commandLink tag it doesn't work because the form is submitted by java script (from the file jsf.js in the jar jsf-impl.jar) as shown below

mojarra.jsfcljs = function jsfcljs(f, pvp, t) {
  mojarra.apf(f, pvp);
  var ft = f.target;
  if (t) {
    f.target = t;
  }
  f.submit();
  f.target 开发者_如何学C= ft;
  mojarra.dpf(f);
};

To solve this problem I copied the jsf.js file under WEB-INF/resources/javax.faces/jsf.js and modified it to trigger the form submit method using jQuery. This works fine but:

1) I don't like the fact that I am touching the jsf.js file since it may change in newer releases of JSF.

2) I don't like the fact that I am using jQuery inside the jsf.js file.

Is there a better solution to solve this problem?


You should use jsf.ajax.*, since it is standard as part of the JSF2 spec. In there you have for example jsf.ajax.addOnEvent(callback) that does what you want.

After you hook in your listener, you can use as much jQuery as you want.

update:

If you want to intercept it from your own JS, without touching their stuff you can do:

(function() {
    var oldjsfcljs = mojarra.jsfcljs;

    mojarra.jsfcljs = function() { 
        console.log('my stuff before');
        oldjsfcljs.apply(this, arguments);
        console.log('my stuff after');
    }
})();


As Bodgan suggested a better solution is to execute the following piece of code when the page is loaded, I don't know what the term is in JS but seems an override for me.

jQuery(function(){
  var oldjsfcljs = mojarra.jsfcljs; // save a pointer to the old function

  mojarra.jsfcljs = function jsfcljs(f, pvp, t) {
    jQuery(jq(f.id)).trigger('submit');
    oldjsfcljs.apply(this, arguments);
  };
});

function jq(myid) {
  return '#' + myid.replace(/(:|\.)/g, '\\$1');
}

Note: the jq() method is only used to escape the special characters in the form ID.

update: the above code seemed to work but if you have parameters in the form it wont so I had to rewrite the mojarra.jsfcljs function as follows:

jQuery(function(){
  mojarra.jsfcljs = function jsfcljs(f, pvp, t) {
    mojarra.apf(f, pvp);
    var ft = f.target;
    if (t) {
      f.target = t;
    }

    // trigger the submit event manually.
    jQuery(jq(f.id)).trigger('submit');

    f.submit();
    f.target = ft;
    mojarra.dpf(f);
  };
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号