mardi 6 juin 2017

How to process http request inside an object literal?

I'm currently learning about design patterns and am refactoring some code to follow the object literal pattern. However, I'm not sure how to process an http request while using this pattern.

Usually I would process the data within the request itself. But is there a way to do the following?

let myObj = {

  makeRequest: function () {
    let request = new XMLHttpRequest()
    request.open('GET', 'url')
    request.onload = function () {
      if (this.status >= 200 && this.status < 400) {
        // somehow this.response gets stored into myObj.returnedData
      }
    }
    request.send()
  },

  returnedData: '',

  anotherFunc: function () {
    // does something with this.returnedData
  }

  init: function () {
    this.makeRequest()
  }
}

myObj.init()

I suspect that maybe I'm going about this all wrong, any pointers appreciated.

Aucun commentaire:

Enregistrer un commentaire