问题
I'm loading jQuery embedded into RichFaces with:
<a4j:loadScript src="resource://jquery.js"/>
Next, I'm loading the FancyBox jQuery plugin with:
<script type="text/javascript" src="/App/fancybox/jquery.fancybox-1.3.4.pack.js"/>
The plugin works ok when the page is first loaded, however after executing an ajax call with
<a4j:jsFunction name="myMethod" data="#{myController.jsonDataToReturn}" action="#{myController.doSomething()}" oncomplete="populateData(data);">
<a4j:actionparam name="selectedTag" assignTo="#{myController.selectedTag}"/>
</a4j:jsFunction>
the plugin stops working. Tests show that the a4j:loadScript
tag is reloaded on every ajax call, thereby reloading the jQuery variable which loses the attached plugin.
The current workaround is to load jQuery by putting a <rich:jQuery query="fn" />
tag somewhere in the page. It does nothing besides forcing jQuery to load, but because it doesn't use a4j, jQuery isn't reloaded on ajax calls.
Still, is there a clean solution for this? I'm using RichFaces 3.3.3 which includes jQuery 1.3.2.
Update:
FancyBox is loaded with:
jQuery(document).ready( function(){
jQuery('.fancyboxLink').live('click',aclick);
});
function aclick(){
jQuery.fancybox({
href: '#{facesContext.externalContext.requestContextPath}/webpage.xhtml',
type:'iframe',
width:710,
height:510,
padding:0,
margin:0,
hideOnOverlayClick:false,
overlayColor:'#000'
});
return false;
}
After the first ajax call, jQuery no longer contains fancybox.
回答1:
First thing you need is loading the script on each ajax request, use a4j:loadScript
for that.
<a4j:loadScript src="/App/fancybox/jquery.fancybox-1.3.4.pack.js"/>
Second: execute that fancybox script when component is being rerendered (ajax call which rerenders part of dom tree containing element with fancybox). I would do that by writing a custom facelets component, like this.
fancyInput.xhtml:
<ui:component xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:c="http://java.sun.com/jstl/core">
<a4j:loadScript src="resource:///App/fancybox/jquery.fancybox-1.3.4.pack.js"/>
<!-- id is passed by component's client as facelet param. -->
<h:commandButton id="#{id}" otherParameters="....."/>
<script type="text/javascript">
jQuery(function() {
// Attaching fancybox to rendered component.
jQuery($('#{rich:clientId(id)}')).live('click',aclick);
});
</script>
</ui:component>
Your page:
<ui:include src="fancyInput.xhtml">
<ui:param name="id" value="anId"/>
<ui:param name="otherParams" value="..."/>
</ui:include>
来源:https://stackoverflow.com/questions/7207901/richfaces-a4jloadscript-clears-jquery-plugins-on-ajax-calls