2
\$\begingroup\$

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.

  1. I have a ConfigViewer javascript class that is responsible for creating, populating and handling events for DOM element.
  2. This class constructor inits the DOM components, and then calls an REST API to get the data to populate these DOM components.
  3. 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);
       }
    });
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
    });
};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.