Accessing `this` in Ajax callback, all within an Object

后端 未结 3 2108
夕颜
夕颜 2020-12-14 12:34

I\'m dealing with a problem about an Ajax callback inside of an Object. Please consider this code :

Search.prototype =
{
    ask : function( query )
    {
           


        
相关标签:
3条回答
  • 2020-12-14 12:51

    You can use the ES5 .bind function to set this correctly:

    $.ajax(...).done(this.loadResults.bind(this));
    

    (use the shim at the above link, or the jQuery $.proxy equivalent on older browsers).

    Alternatively, add context: this to the $.ajax options:

    $.ajax({
        ...,
        context: this
    }).done(this.loadResults);
    

    Note that in either case you will override jQuery's default behaviour of passing the ajax option object in this.

    p.s. it's also good practise to return the result of the $.ajax() chain so that the user of your object can chain additional callbacks (e.g. a .fail handler) to it.

    0 讨论(0)
  • 2020-12-14 13:00

    There are several ways to do this.

    You can set the context setting for the ajax options:

    jQuery.ajax context setting

    $.ajax({
        context: this
    

    Function.prototype.bind

        .done(function (res) {
    
        }.bind(this));
    

    However, this is not as widely supported as...

    jQuery.proxy

    Created for this purpose.

        .done($.proxy(function (res) {
    
        }, this);
    

    Assigning this to another value

    var self = this;
    $.ajax({
    /* snip */
    .done(function (res) {
        self.loadResults(res);
    

    This is commonly done in JavaScript to give access to this in lower scopes.

    Arrow functions with lexical binding

    $.ajax({
    /* snip */
    .then(res => this.loadResults(res));
    
    0 讨论(0)
  • 2020-12-14 13:04

    You can use the $.ajax() context object here like:

    $.ajax({
        url : 'http://api.deezer.com/search/track/',
        context: this,
        ...
    }).done(function (res) {
        this.loadResults( res );
    });
    
    0 讨论(0)
提交回复
热议问题