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);
}
});
}
1 Answer 1
It doesn't look like your class has any data, so I must question what's the point. Any instance of the class would be equal to each other.
Your constructor is also doing a lot of real work, constructors should just initialize the object.
You can also do what you are doing without manual closure plumbing by using jQuery's proxy:
function ConfigViewer() {
this.createUIComponents();
this.ajaxLoadData("/adminData").then($.proxy(this.successHandler, this));
}
ConfigViewer.prototype.successHandler = function( data ) {
this.populateUICoponents(data);
};
ConfigViewer.prototype.ajaxLoadData = function(url) {
return $.ajax({
url : url
});
};