访问`this`在Ajax回调,所有的对象中 [英] Accessing `this` in Ajax callback, all within an Object

查看:100
本文介绍了访问`this`在Ajax回调,所有的对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处理有关的Ajax回调对象的内部问题。 请考虑把这张code:

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

Search.prototype =
{
    ask : function( query )
    {
        // Display loader
        $('.loader').show();

        $.ajax({
            dataType : 'jsonp',
            type : 'GET',
            url : 'http://api.deezer.com/search/track/',
            data : {
                output : 'jsonp',
                q : query
            }
        }).done(function(res) {

            this.loadResults( res );
            // [Error] Object success has no method 'loadResult'

        });
    },

    loadResults : function (res)
    {
        // Hide loader
        $('.loader').hide();

        console.log( res );

        // doing some stuff
        // ...
    }
}

var search = new Search();
search.ask( 'eminem' );

我得到一个错误对象的成功有没有一种方法loadResult ,这是有道理的回调是一个匿名的jQuery功能的一部分。

I get an error Object success has no method loadResult , which makes sense as the callback is part of an anonymous jQuery function.

可是如何才能让我最初的对象实例?

But how to get my initial object instance ?

我一直在试图用VAR的=这一点; Ajax调用过,但I't不会适用于同样的原因。

I've been trying with a var that = this; before the Ajax call, but I't won't works for the same reasons.

我不知道这是否是可能做到这一点,或者如果问题来自于我的code的全球性组织。随时提醒我关于最佳做法:)

I don't know if it's possible to do this or if the problem comes from my code global organization. Feel free to advise me about the best practices :)

由于被提前。

我混淆了一些东西在我的code,我虽然是不必要的,张贴在这里,但我终于有点早期发现的问题,我的code。 我们对此深感抱歉。

I obfuscated some things in my code which I though it was unnecessary to post here, but I finally found out the problem a little bit earlier in my code. Sorry about that.

下面是我的全部code,这是现在的工作:

Here's my full code, which is now working :

define(['jquery'], function($) {

    var Search = function()
    {
        this._keyDownTimer = 0;
        this._searchDelay = 1000; // ms
    };

    Search.prototype =
    {
        // The init function that I though it was unnecessary to post here. Sorry :/
        init : function()
        {
            $('#q').on('keydown', (function(evt) {

                clearTimeout( this._keyDownTimer );

                this._keyDownTimer = setTimeout( (function() {

                    this.ask( $('#q').val() );

                }).bind( this ), this._searchDelay); /* <-- Here's the solution.
                                                        I forgot to bind `this`
                                                        to the timeout callback function,
                                                        so the `this` under all of my code
                                                        was referring to the anonymous function
                                                        of this callback. */

            }).bind( this ));
        },

        ask : function( query )
        {
            // Display loader
            $('.loader').show();

            console.log(this); // Now `this` refers to my object :)

            var req = $.ajax({
                dataType : 'jsonp',
                type : 'GET',
                url : 'http://api.deezer.com/search/track/',
                context : this,
                data : {
                    output : 'jsonp',
                    q : query
                }
            });

            req.done(function(res) {
                this.loadResults(res);
            });
        },

        loadResults : function (res)
        {
            // Hide loader
            $('.loader').hide();

            // doing some stuff
            // ...
        }
    };

    return new Search;

});

感谢您的回复,它确实有帮助。

Thanks for your replies, it really helped.

铅解决。

推荐答案

您可以使用ES5 <一href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"相对=nofollow> .bi​​nd 功能设置正确的:

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

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

(使用垫片在上面的链接,或jQuery的 $。代理等同于旧的浏览器)。

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

另外,添加背景:本 $ AJAX 选项:

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

请注意,在这两种情况下,你将覆盖传递阿贾克斯选择对象的jQuery的默认行为,这种

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

P.S。这也是很好的做法返回 $。阿贾克斯()链的结果,使你的目标用户可以链额外的回调(如 .fail 处理)给它。

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.

这篇关于访问`this`在Ajax回调,所有的对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆