Last active
August 28, 2019 08:44
-
-
Save douglascayers/3c834893f5777a7989ea5fa18bf543b0 to your computer and use it in GitHub Desktop.
Visualforce and JavaScript design pattern to handle page load and ajax rerendering events.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<apex:page extensions="SomeController"> | |
<script src="{!$Resource.jquery224}"></script> | |
<script>$j = jQuery.noConflict();</script> | |
<apex:form> | |
<apex:outputPanel id="someSection"> | |
... stuff here ... | |
<button onclick="showSpinner();someFunction();"/> | |
</apex:outputPanel> | |
<apex:actionFunction | |
name="someFunction" | |
action="{!someApexFunction}" | |
rerender="someSection,jsBlock" | |
oncomplete="onPageRender();"/> | |
</apex:form> | |
<apex:outputPanel id="jsBlock" style="display:none;"> | |
<!-- | |
This javascript block is wrapped in apex:outputPanel | |
so that when the page rerenders and whatnot that | |
these variables can get recalculated too. | |
Otherwise, after an apex:actionFunction completes and modifies | |
apex variables any non-rererendered sections don't pick up the changes. | |
The magic of javascript is that when this section rerenders it | |
re-declares and assigns new values to these variables. | |
JavaScript elsewhere on the page when it runs and references these | |
variables then that code will use the updated values. | |
--> | |
<script> | |
var VARIABLE_A = '{!someVariableA}'; | |
var VARIABLE_B = '{!someVariableB}'; | |
</script> | |
</apex:outputPanel> | |
<script> | |
$j(function() { | |
onPageLoad(); | |
onPageRender(); | |
}); | |
/** | |
* Should be called exactly once per full page load. | |
* Good place to attach listeners. | |
* Do not call this after async calls, use onPageRender() instead. | |
*/ | |
function onPageLoad() { | |
$j('<selector>').click( function() { | |
// handle click event | |
}); | |
$j(window).on( "message onmessage", function( e ) { | |
// listen for window message to be posted | |
}); | |
} | |
/** | |
* When apex:actionFunctions complete and rerender the page then should | |
* call this method for any post-render javascript processing. | |
* This is NOT a good place to attach listeners, use onPageLoad() instead. | |
*/ | |
function onPageRender() { | |
if ( VARIABLE_A == 'true' ) { | |
// do something | |
} | |
if ( VARIABLE_B == 'someValue' ) { | |
// do something else | |
} | |
// maybe hide a status indicator or something | |
hideSpinner(); | |
} | |
function showSpinner() { ... } | |
function hideSpinner() { ... } | |
</script> | |
</apex:page> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment