简体   繁体   中英

Javascript Callback Async Ajax YUI 3

I'm trying to reduce code and simplify somethings by having a reusable method for making async ajax calls. I'm actually switching to YUI 3 from jQuery and cleaning stuff up in the process. This is probably super easy for you javascript guys to spot, but I've been trying to figure out how I can get my callback called without leaking memory. If I watch IE in Task Manager memory goes up very fast (the function is called every 1.5 seconds).

Basically, I have my normal web page that has the function I want called after the ajax completes. I'm updating the UI from there and setting other variables that are only part of the page. I have a javascript file where I'm putting the method that actually makes the ajax call. When I use the callback that I'm passing into that method it's leaking.

javascript file:

function doAjaxRequest(url, callback) {
    YUI().use('io',
        function (Y) {
            var cb =
            {
                timeout: 5000,
                on: {
                    success: function (x, o) {
                        callback(o.responseText);
                    },
                    failure: function (x, o) {
                        callback("");
                    }
                }
            }

            Y.io(url, cb);
        });
}

web page:

doAjaxRequest(myUrl, showContent); // Called every couple seconds

        function showContent(o) {
            document.getElementById('ajaxcontent').innerHTML = o;
            // Other Stuff Removed    
        }

If I comment out the callback line it doesn't leak. I must have to make the callback another way, I just don't know what that is.

The problem is that you are creating a new YUI instance with each call to doAjaxRequest . Structure your code like this instead:

YUI().use('io', function (Y) {
function doAjaxRequest(url, callback) {
    // ...
}

window.doAjaxRequest = doAjaxRequest;
});

This will create only one YUI instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM