lennyklb
lennyklb

Reputation: 1367

Call object method right after its construction in Javascript

I'm writing a class that, among its properties, has a dynamically loaded DOM elements. A very simple overview of this flow:

  1. Window is loaded
  2. Object of class SomeClass is created (With (2.1) some attributes, and (2.2) a DOM Element dynamically loaded using AJAX)
  3. Something with these DOM element properties is done (transformations etc.) optionally

Like this:

window.addEventListener("load",function(){ // Step 1
  someObject = new someClass("element_id") // Step 2.1
  someObject.loadToDOMThroughAJAX(function(){ // Step 2.2
      someObject.optionalMethodAfterConstruction(); // Step 3
  }); 
})

Edit: The snippet for optionalMethodAfterConstruction() :

someClass.prototype.optionalMethodAfterConstruction = function(){
  var element = this.element.querySelector(".someClass")
  element.setAttribute("transform","translate(20,20)")
}

Edit2: Snippet for loadDOMThroughAjax():

someClass.prototype.loadDOMThroughAjax= function(){
  obj = this;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "/path/to/html", true);
  ajax.send();
  ajax.onload = function(e) {
    obj.element.innerHTML = ajax.responseText
  }
}

However, when step 3 is executed, the DOM elements have not yet been loaded in step 2.2, which causes step 3 to fail because it relies on a succesful document.querySelector() call. The DOM element with class .someClass is loaded dynamically and should be present when that method is called, but it isn't. Manually calling the method does work.

I feel like I'm close, but I'd like to know how to properly do this and what I'm missing.

I can't attach this to the constructor itself because it should not be applied to every object, just some.

No jQuery.

Upvotes: 1

Views: 68

Answers (1)

Tudor Merlas
Tudor Merlas

Reputation: 412

From your second edit I see that you don't actually call the function you send as parameter in step 2.2.

someObject.loadToDOMThroughAJAX(function(){ // Step 2.2
  someObject.optionalMethodAfterConstruction(); // Step 3
}); 

But your function is as follows:

someClass.prototype.loadDOMThroughAjax= function(){
  obj = this;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "/path/to/html", true);
  ajax.send();
  ajax.onload = function(e) {
    obj.element.innerHTML = ajax.responseText
  }
}

You should also call the parameter as par of your onload function thusly:

someClass.prototype.loadDOMThroughAjax= function(CALLBACK){
  obj = this;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "/path/to/html", true);
  ajax.send();
  ajax.onload = function(e) {
    obj.element.innerHTML = ajax.responseText
    if (someConditionIsTrue) {
      CALLBACK();
    }
  }
}

Upvotes: 1

Related Questions