JSF 2.0 javascript onload/oncomplete

2020-08-01 02:07发布

问题:

I'm working with Myfaces 2.0 after a long project using MyFaces 1.1 + Tomahawk + Ajax4JSF. 2.0 is definitely a huge improvement. Although I can't seem to get an onload javascript to work. I stuck this in my head:

<script type="text/javascript">
    window.onload = function () {
        var fileDownload = document.getElementById('userManagementForm:fileDownload');
        if (fileDownload.value == 'true') {
            fileDownload.value = false;
            window.open('Download');
        }
    }                   
    </script>

But it doesn't execute. I looked a bit at the source myfacecs JS and I noticed they do some stuff with the onload. Didn't get too much into the details but it seems to block my attempt at overriding the onload event. Is there another way around this, maybe a direct call to the JSF library?

Another question, sort of on the same topic. Ajax4JSF had an attribute "oncomplete" which would let you run some Javascript after the Ajax request completed. Is there an equivalent in MyFaces 2.0 with the f:ajax? Come to think of it I haven't tried event="oncomplete", maybe it'll work.

回答1:

Okay so I figured it out.

Loading the script at the top of page later gets overridden

If I load the script at the end of the page it overrides the onload, but it also breaks the JSF mechanism. So the better solution was to user JSF's onload thing and put the script at the end of the page. After digging through the JSF source a bit I found the function.

<script type="text/javascript">
        myfaces._impl.core._Runtime.addOnLoad(window, checkDownloadFile);
</script>

And of course I had to define checkDownloadFile which does what I had in the original post.

I also figured out for the oncomplete. The f:ajax tag has an onevent attribute which gets called 3 times. Once before execution and twice after. I believe once immediately after completing the request, then again after updating the page components. The callback function takes an event parameter which has a status. So in your callback function you check the status to decide whether or not to do something. The statuses are begin, complete, and success. So for my case I have:

<f:ajax execute="userManagementForm" event="click" onevent="myEvent" render="userManagementForm:results userManagementForm:workarea userManagementForm:fileDownload" />

And then the script:

    function myEvent(e) {
        if (e.status == 'success') {
            checkDownloadFile();
        }
    }