0

假设我有:

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');
        }
});

有没有办法以某种方式更整齐地包装它 - 就像我真正改变的唯一变量是 GET / POST,所以我在想这样的事情:

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

这可能吗?

我对JS还不够熟悉。

4

2 回答 2

0

只需将逻辑包装在另一个函数中,如下所示:

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');
        }
});
}

getData('POST')并用or调用它getData('GET')

于 2013-05-19T11:18:33.763 回答
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');
            }
    });
}

为了提高代码质量,您应该:

  • 做一个检查typeof callback === "function"以确保传入的参数是一个函数。
  • callback.call(kango,data);传递kango作为上下文。里面的回调函数可以this用来访问。这将创建一个更松散耦合的代码。
于 2013-05-19T11:57:09.987 回答