I'm using this pattern (for want of a better word) repeatedly in my code to call a REST API in my javascript code. Some particulars of the code below.
- I have a ConfigViewer javascript class that is responsible for creating, populating and handling events for DOM element.
- This class constructor inits the DOM components, and then calls an REST API to get the data to populate these DOM components.
- I need to handle the response to this API from my instance of ConfigViewer
My question is related to the way I have the getAdminDataSuccessHandler() method to return a function that is called when the REST API succeeds: Is this the cleanest way to handle the response of the API call ?
function ConfigViewer() {
this.createUIComponents();
this.ajaxLoadData("/adminData", this.getAdminDataSuccessHandler());
}
ConfigViewer.prototype.getAdminDataSuccessHandler = function() {
var self = this;
return function(data) {
// Handle successful data retrieval
self.populateUICoponents(data);
}
}
/**
* Execute the API in ajaxy fashion.
*/
ConfigViewer.prototype.ajaxLoadData = function(url, onSuccessHandler) {
$.ajax({
url : url,
success : function(jsonData, textStatus, XMLHttpRequest) {
onSuccessHandler(jsonData);
}
});
}