Home  >  Q&A  >  body text

javascript - 怎样做ajax返回数据时的解耦?

var ajaxProcess = function(xxx, yyy, zzz){
this.strResultDatas = "";

this.submit = function(){
    createXMLHttpRequest();         
    this.url = url;
    xmlHttp.onreadystatechange=this.searchResult; 
    xmlHttp.open("POST",url ,true); 
    xmlHttp.setRequestHeader("If-Modified-Since","0");               
    xmlHttp.send(null);
};

this.searchResult = function(){
    if(xmlHttp.readyState==4 && xmlHttp.status==200){
        this.strResultDatas = xmlHttp.responseText;
        // 此处可对返回的数据进行更进一步的处理。
        //TODO

        // 为了保持类的纯净性,我想将处理过程抛到其它的函数中处理。
        // 
        // 但此处是ajax异步获取的结果集,外部调用时调用的是submit(),
        // 在searchResult()获得返回值时,
        // 怎么才能通知外部函数 searchResult()已经有了返回值呢?
    }

}

迷茫迷茫2640 days ago625

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 12:47:15

    实现一个事件分派机制。

    实现一个EventDispatcher类,在你的ajaxProcess类里面dispatchEvent()。

    然后在外部注册对相应事件的响应addEventListener()。

    雏形如下:

    function EventDispatcher() {
        this.listeners = {};
    }
    
    EventDispatcher.prototype = {
        addEventListener: function (type, listener) {
            this.listeners[type].push(listener);
        },
        dispatchEvent: function (e) {
            var listeners = this.listeners[e.type];
            for (var i = 0, len = listeners.length; i < len; i++) {
                listeners[i].apply(this, arguments);
            }
        }
    }
    

    reply
    0
  • Cancelreply