Execute jQuery widget method inside a ajax request / setTimeout

432 views Asked by At

I try to call another method inside a setTimeout function, but it do not find the method if I use this.install() inside setTimeout. I have tried some solutions but seems not to solve it, so therefor I ask here.

The code I have, remember to look at the comments what I try to do:

jQuery(window).load(function () {

$.widget( "testing.updater", {

        options: {

        },

        _create: function() {

            //
            this.element.addClass('text');

            //
            this.downloadFiles('bootstrap');

        },

        downloadFiles: function(packagen) {
            var ajax = $.ajax({
                type: "POST",
                url: "responses/test.php",
                data: "download=" + packagen,
                success: function(data) {
                    var obj = jQuery.parseJSON( data);

                    $('.text').append('Downloading files...<br>');
                    $('#updateBtn').attr("disabled", true);

                    if (obj.downloaded) {
                        setTimeout(function(message){
                            $('.text').append(obj.message+'<p><p>');
                            // Down here I want to call another method
                            // like this.install(); <.. but ain't working..
                        }, 5000);
                    } else {
                        return $('.text').append('<p><p> <font color="red">'+obj.message+'</font>');
                    }

                }
            });

        },

        install: function() {
            // I want to run this method inside
            // prev method, look above comment
        },

    });

    $('#updateBtn').on('click',function(){
        var test = $('.updater').updater();
        test.updater();
    });
});
1

There are 1 answers

1
T J On BEST ANSWER

Inside the setTimeout callback, this refers to the global - window object. You can save a reference to the object before timeout like var that = this and use it for the referencing the object inside timeout,

or you can pass the context using the bind() method like:

setTimeout(function () {
  console.log(this)
}.bind(obj), 10);