Overloading functions inside SharePoint standard script libraries

We had the requirement to hook into events that occur within SharePoint script objects, specifically when a new calendar item is created. One way of doing this is to simply override the action with your code, but that will make the existing function break. Alternatively, you can edit the standard script file or copy the contents of the method and change it into a new signature. Neither of these are good methods as the code may change in an upcoming release or service pack.

Instead, we copy the old function name into a temporary variable as:

var oobCalendarEvent;

if (!oobCalendarEvent) {
	// Save the original OOB function to a local temporary handler
	oobCalendarEvent = 
	SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
}

After that, we can override the existing method:

SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function ($p0, $p1) {
	// Custom code goes here and will fire 
	// whenever the original calendar state changes
};

And finally, we implement some logic, and call the original method either before or after our own code. Here is the complete code (ignore the log methods that are using a custom logger).

function overrideCalendarRenderingEvents() {
        /// <summary> Overrides the OOB rendering events to ensure we add our events.</summary>
        log.add("Overriding events.", 
		"calendar.legend.overrideCalendarRenderingEvents");

        try {
            if (!oobCalendarEvent) {
                // Save the original OOB function to a local temporary handler
                oobCalendarEvent = SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
            }

            SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function ($p0, $p1) {
                log.add("Triggered", "calendar.legend.overrideCalendarRenderingEvents");

                // Call this method to render events on the page. using original handler 
                oobCalendarEvent.call(this, $p0, $p1);

                // Render using our own logic
                updateCalendarUI();
            };
        } catch (e) {
            log.add("Unable to override SP calendar rendering methods.", 
		"calendar.legend.overrideCalendarRenderingEvents", e);
        }
    }

Hope this helps.