1

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();
    });
});
Spl1tz
  • 37
  • 1
  • 6
  • Take a look at this question/answer: http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback – SpaceDog Dec 15 '14 at 09:46

1 Answers1

1

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);
T J
  • 42,762
  • 13
  • 83
  • 138
  • I'm sure I tried set a variable outside but did not work.. Well thanks a lot for this, worked as a charm!! :) – Spl1tz Dec 15 '14 at 10:13