widgetVar cannot be used in p:fileUpload

守給你的承諾、 提交于 2021-02-16 18:51:29

问题


I want to remove the error message when choosing a wrong type of file. I followed the link http://forum.primefaces.org/viewtopic.php?f=3&t=23853 .

<p:fileUpload fileUploadListener="#{userProfileUpdateController.upload}"         
    widgetVar="fileuplaodWgt"                     
    allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
    description="Select Images"
    update="userPhoto"
    mode="advanced"/>

and I import <h:outputScript name="library.js" library="script"></h:outputScript>

In library.js

$(document).ready(function(){
   alert(fileuplaodWgt);
   fileuplaodWgt.buttonBar.find("button.cancel").bind("click", function(e){
   clearInvalidFileMsg();
    });
});

function clearInvalidFileMsg(){
    fileuplaodWgt.uploadContent.find("tr.ui-state-error").remove();
 }

After writing above, file upload is not shown in my page. When I trace the my library.js file, I found fileuplaodWgt ReferenceError: fileuplaodWgt is not defined. I tried in mozilla and chrome. None of them shows my file upload. Can you help me what I am wrong???


回答1:


PrimeFaces initializes widget vars on DOM ready as well by $(function()). The <script> containing the command is rendered directly after the component. So, if your $(document).ready() is invoked before the widget var one, then it won't find the widget var because it's initialized later. You need to ensure that your $(document).ready() is invoked after the component is rendered. One of the ways is relocating the script to the end of HTML <body> by target="body".

<h:outputScript name="library.js" library="script" target="body" />

This way the script is loaded and initialized when the end of document is reached, thus after all widget var initializations.

Another way is to use $(window).load() instead of $(document).ready(), but this is clumsy and potentially slower as it's only invoked when all images referenced in the document are loaded.


Unrelated to the concrete problem, the way you're using the resource library is not right. Please carefully read What is the JSF resource library for and how should it be used? and just use

<h:outputScript name="script/library.js" target="body" />

You've by the way also a disturbing typo in the widget var name not further related to the problem. It's upload, not uplaod.



来源:https://stackoverflow.com/questions/14232334/widgetvar-cannot-be-used-in-pfileupload

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