0x_Anakin
0x_Anakin

Reputation: 3269

Javascript callback not firing when using this

Hello I have this code which works fine

var app = {

    callback: null,
    jqmReady: null,
    pgReady: null,

    // Application Constructor
    initialize: function(callback) {
        this.callback = callback;
        this.jqmReady = $.Deferred();
        this.pgReady = $.Deferred();
        this.bindEvents();
    },

    bindEvents: function() {
        document.addEventListener('deviceready', app.pgReady.resolve, false);
        $(document).on("pageinit", app.jqmReady.resolve);
        $.when(app.jqmReady, app.pgReady).then(app.isReady);
    },

    isReady: function() {
        app.callback();
    }

};

code is being initialized like this:

    app.initialize(function(){
        navigator.notification.alert('Hello there!', function(){}, 'Notify', 'Ok');
    });

however my isReady function was like this at first and the callback was not called:

    isReady: function() {
        this.callback();
    }

Why is this happening ? isn't the scope of this = app inside isReady() like in the initialize() function ? Could someone explain to me why it doesn't work with this.callback() ?

Upvotes: 0

Views: 167

Answers (1)

Eli Gassert
Eli Gassert

Reputation: 9763

You've created an object, not a class or an instance of a class. Change your this to app throughout your initialize function. You're doing that already in your isReady and bindEvents functions. So keep that going in initialize.

Upvotes: 1

Related Questions