Search code examples
javascriptjqueryajaxthisobject-literal

Javascript - how to bind 'this' inside an ajax call to the object literal


I have an object literal router, containing an ajax call. I want to call other functions this.printMovies() inside the ajax call but this refer to the ajax object.

How do I escape it and make this refer to the router object itself?

var router = {  

    //...
    init : function() {
        this.getData("api/movies", "movies", callback);
    },
    getData : function (url, htmlType, callback) {
        $.ajax({
            url: url,
            dataType: 'json',
            success: function (response) {
                if (response && response.length > 0) {
                    this.printMovies(response, callback); //'this' refers to ajax
                    this.printMovies(response, callback).bind(this) //still doesn't work
                }
            },
            error: function (response) { console.log("Error:" + response); }
        });
    },
    printMovies : function(){

    },  
}

Solution

  • Pass context option to ajax:

    $.ajax({
      context: this,
      /* other options */
    }
    

    Now inside ajax callbacks, this will refer to router object.