0

Let's say I have:

var details = {
        method: 'POST',
        url: 'http://example.com/',
        async: true,
        params: {'param1': '1', 'param2': '2'},
        headers: {'If-Modified-Since': 'Sat, 1 Jan 2000 00:00:00 GMT', 'Cache-Control': 'max-age=0'},
        contentType: 'text'
};

kango.xhr.send(details, function(data) {
        if (data.status == 200 && data.response != null) {
                var text = data.response;
                kango.console.log(text);
        }
        else { // something went wrong
                kango.console.log('something went wrong');
        }
});

Is there a way to wrap it more neatly somehow - like the only variables I really change is GET / POST, so I'm thinking something like:

call('POST', function(data) {});

Is this possible?

I'm not familiar enough with JS.

dsp_099
  • 5,801
  • 17
  • 72
  • 128

2 Answers2

0

Just wrap the logic in another function like this:

function getData(method) {
var details = {
        method: method,
        url: 'http://example.com/',
        async: true,
        params: {'param1': '1', 'param2': '2'},
        headers: {'If-Modified-Since': 'Sat, 1 Jan 2000 00:00:00 GMT', 'Cache-Control': 'max-age=0'},
        contentType: 'text'
};

kango.xhr.send(details, function(data) {
        if (data.status == 200 && data.response != null) {
                var text = data.response;
                kango.console.log(text);
        }
        else { // something went wrong
                kango.console.log('something went wrong');
        }
});
}

and call it with getData('POST') or getData('GET').

Benny Ng
  • 328
  • 2
  • 6
0
function Call(method,callback){
    var details = {
            method: method,
            url: 'http://example.com/',
            async: true,
            params: {'param1': '1', 'param2': '2'},
            headers: {'If-Modified-Since': 'Sat, 1 Jan 2000 00:00:00 GMT', 'Cache-Control': 'max-age=0'},
            contentType: 'text'
    };

    kango.xhr.send(details, function(data) {
            if (data.status == 200 && data.response != null) {
                  if (typeof callback === "function") {
                    callback.call(kango,data);
                  }
            }
            else { // something went wrong
                    kango.console.log('something went wrong');
            }
    });
}

To improve code quality, you should:

  • Do a check typeof callback === "function" to ensure that the parameter passed in is a function.
  • callback.call(kango,data); to pass the kango as the context. Inside the callback function you can use this to access. This would create a more loosely coupled code.
Khanh TO
  • 48,509
  • 13
  • 99
  • 115