Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - Scope in an $.ajax callback function

If I am using this code why has the scope changed for the "doStuff" alert? Is there a way that I can make sure that the scope is my object and not the Window object?

Here is the same code in jsfiddle.

(function ($) {
    var c$ = {};

    c$.TestScope = function () {

        this.doAjax = function (onComplete) {
            var self = this;
            $.ajax({
                url: 'badurl',
                complete: function (data) {
                    alert('doAjax2 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
                    onComplete(data);
                }
            });
            alert('doAjax1 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());  
        };

        this.doStuff = function (data) {
            var self = this;
            alert('doStuff self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
        }

    };

    c$.oTestScope = new c$.TestScope();
    c$.oTestScope.doAjax(c$.oTestScope.doStuff);
})(jQuery);?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be able to specify the this value as the context in your $.ajax() parameters:

var c$ = {};

c$.TestScope = function() {

    this.doAjax = function(onComplete) {

        alert('doAjax1 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());

        $.ajax({
            url: 'badurl',
            context: this,
            complete: function(data) {
                alert('doAjax2 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
                onComplete.call(this, data);
            }
        });
    };

    this.doStuff = function(data) {
        alert('doStuff this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
    }

};

c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);

Edit I made a fiddle for this and verified that it works properly. There's no messing around with an extra self parameter or having to muck around with closures to keep your variables.

Part of what you were missing was calling onComplete.call(this, data) to invoke doStuff().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...