编程语言
首页 > 编程语言> > javascript – 使用ajax在js中的OOP方法

javascript – 使用ajax在js中的OOP方法

作者:互联网


嗨,我有一个对象:

function Page(daoService) {
    this.daoService = daoService;
    this.gamesList = this.daoService.getGamesList();
}

// Rendering thumbs for main page
Page.prototype.renderThumbs = function(idContainer){
    var container = document.getElementById(idContainer);
    for (var i = 0; i < this.gamesList.length; i++) {
        var thumbNode = document.createTextNode("<div class='thumbIcon'></div>");
        thumbNode.style.backgroundImage = Const.PATH_THUMBS + this.gamesList.gameTitleseo;
        container.appendChild(thumbNode);
    }
};

而且我的代码中还有使用此对象的函数:

document.onreadystatechange = function() { 
    if (document.readyState == "interactive") { 
        // Initialization of elements
        // Setting global dao service
        var daoService = AjaxService();

        // Initialization for page object
        var page = new Page(daoService);
        page.renderThumbs("homePageContainer");
    } 
} 

这里的问题是,当我调用page.renderThumbs时,字段this.gamesList仍然没有初始化,因为它没有从服务器获得ajax响应.你能帮助我处理我需要改变的方法吗?谢谢

解决方法:

您需要在daoService上设置getGamesList来处理异步方法.这是我的意思的粗略草图:

DaoService.prototype.getGamesList = function(callback) {

    var self = this;

    // Has the gamesList been populated by a previous call to this function?
    if (this.gamesList) {
        // The gamesList property has values, call the callback.
        callback(this.gamesList);
    }
    else {
        // The gamesList was not populated, make the ajax call.
        $.ajax('URL').done(function(data) {
            // Handle data coming back from the server.
            self.gamesList = data;
            callback(this.gamesList);
        });
    }


}

然后,您可以使用renderThumbs中的getGamesList方法调用,如下所示:

Page.prototype.renderThumbs = function(idContainer){
    var container = document.getElementById(idContainer);

    // The anonymous function will be called whether the list was
    // already populated in daoService or an ajax call is made.
    this.daoService.getGamesList(function(gamesList) {
        for (var i = 0; i < gamesList.length; i++) {
            var thumbNode = document.createTextNode("<div class='thumbIcon'></div>");
            thumbNode.style.backgroundImage = Const.PATH_THUMBS + gamesList[i].gameTitleseo;
            container.appendChild(thumbNode);
        }
    });
};

标签:javascript,ajax,oop,document-ready
来源: https://codeday.me/bug/20190830/1770033.html