In the last post we covered some introductory topics for creating your own JavaScript utility library, which wraps functionality for Ajax. We’ll start where we left off. Our first step will be to add a few tweaks to our library to make it more usable:
var mySiteAjax = ( function( $ ) {
return (
function( params ){
var settings = $.extend({
url: "",
spinner: undefined,
dataType: "html",
data: "",
type: "GET",
cache: false,
success: function() { }
}, params );
$.ajax({
beforeSend: function() {
$( settings.spinner ).show();
},
url: settings.url,
dataType: settings.dataType,
type: settings.type,
data: setting.data,
success: settings.success,
complete: function() {
$( settings.spinner ).hide();
}
});
}
);
})(jQuery);
We’ve done two things to our old example. We’ve added new parameters for type and data that could be passed in. Additionally, we’ve removed a named function and returned an object literal. This enables easier usage:
mySiteAjax({
url: "myUrl",
success: function( data ) {
//do something with the data here
}
});
Although a good start, this solution is not yet satisfactory as we are not yet handling errors in any capacity. How do we handle errors and display messages to the user? Additionally showing and hiding of loading notification images is present but not customizable. What if a page doesn’t want to do a simple showing and hiding of load images? How can we decouple the notifications from our Ajax component library?