When reading the chapter on the ajaxguessnumber example app and analysing the code, I was surprised at the choice of writing a custom js-function "msg" to get rid of the stale result. Certainly, this allows the demonstration of the h:commandButton's onevent attribute, but:
- it doesn't seem like a clean solution to me (it doesn't seem very refactoring-friendly because of the 2 getElementById("hard-coded HTML element ID") calls),
- it doesn't explain the inclusion of the commented-out code <f:ajax execute="userNo" render="result errors1" /> within the code AND the tutorial chapter.
It looks more like a quick fix by one person (developer) that was later commented on by another person (who wrote the tutorial chapter).
If one were to want to rewrite the code as it was perhaps originally intended (as is perhaps still visible in the commented-out code aforementioned), I could think of the following two possibilities:
- Only render the outputText if there was no validation error.
- Change the scope of the ManagedBean from @SessionScoped to @RequestScoped
The first solution would look something like the following. For it to work with Ajax, the outputText would need to be wrapped in a container such as h:panelGroup and the f:ajax render attribute would need to refer to the panel's ID ("outputGrid"):
The second solution changes the design altogether. I'm not sure why you would want @SessionScoped for this example in the first place. @RequestScoped seems more appropriate and solves the problem of hiding the "stale output" of the "result" outputText element.