h:commandLink not firing the form.submit event

别等时光非礼了梦想. 提交于 2019-12-11 06:26:15

问题


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 = 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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7568154/hcommandlink-not-firing-the-form-submit-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!