Sunday, August 15, 2010

Extend APEX 4.0 JS using trigger events

APEX 4.0 has introduced JavaScript "trigger events" such as apexbeforerefreshapexafterrefresh and apexbeforepagesubmit.
I'm using them to show a "loading" mask on regions when Partial Page Refresh (PPR) is enabled by clicking on the next rows button, or clicking on the heading to sort by a column.
You can see a live demo of Over-riding APEX JS and using APEX event triggers.
The JavaScript to add this effect is very brief, but there's a lot of concepts to understand.
To implement just copy into your application's JavaScript.

// Copy the APEX function to a new name, so we can override the original.
var apexInitReport = initReport;

// Extend the APEX function by over-riding with our own version and adding functionality
initReport = function(pRegionID, pInternalRegionID, pStyleMouseOver, pStyleChecked) {
   // we can call still call the original (renamed) version to use the existing functionality
   apexInitReport(pRegionID, pInternalRegionID, pStyleMouseOver, pStyleChecked);

   // APEX wraps PPR regions with a DIV with id report_xxx_catch, xxx being the region number
   var c = 'report_' + pInternalRegionID + '_catch';

   // proceed if the PPR region exists
   if (apex.jQuery('#'+c).length) {
      // find the parent DOM node for the PPR
      var p = apex.jQuery('#'+c).parent();

      // Add a bind event to the parent, since the wrapper is deleted on each refresh action.
      // This uses jQuery "live" binding, taking advantage of event bubbling up the DOM hierarchy.
      // ExtJS has more a advanced Event handler.
      apex.jQuery(p).bind('apexbeforerefresh', function(){
          // add a mask when any PPR actions happen 
          // NOTE: this is using the ExtJS library, jQuery users will need to do more work here.
          new Ext.LoadMask(c).show();
      });

   }
}

Over-riding the original initReport function means I don't have to add a call to it in my pages - APEX already does that for me.
Another advantage is that it is automatically applied to all my PPR reports, regardless of what report template I use.

Those of you with sharp eyes will note the "Go to row" item in the bottom of the screenshot.
I've added extra functionality to allow me to jump to any row I like.
I'll be discussing this and other ideas at OpenWorld this year, as well as in my upcoming book on APEX 4.0 with Ext JS.