简体   繁体   中英

Setting a variable after a successful ajax call

In java you can reference an outer class by stating its name followed by this.

class A {
    void A() {

    }
    class B {
        void B() {
            A.this.A();
        }
    }
}

Now I am attempting to do something similar in javascript. Bellow I have constructor that makes an ajax call. This ajax call if successful sets the get method and the assets of the AssetManager.

function AssetManager(path) {

    this.assets = {};

    this.get = function(tag,name) {
        return 0;
    };

    $.ajax({
        url: path,
        dataType: 'json',
        success: function(o) {
            if (o.sprite) {
                var keys = Object.keys(o.sprite);
                for (var i = 0; i < keys.length; i++) {
                    var obj1 = keys[i];
                    AssetManager.this.assets.sprite[obj1] = new Image();
                    AssetManager.this.assets.sprite[obj1].src = o.sprite[obj1];
                }
            }
            AssetManager.this.get = function (tag, name) {
                return assets[tag][name];
            }
        }
    });
}

You have to create variable and point it to this prior executing ajax and access it within success handler:

function AssetManager(path) {
  // ......
  // Set this object to me variable
  var me = this;

  $.ajax({
    url: path,
    dataType: 'json',
    success: function(o) {
        if (o.sprite) {
            var keys = Object.keys(o.sprite);
            for (var i = 0; i < keys.length; i++) {
                var obj1 = keys[i];
                me.assets.sprite[obj1] = new Image();
                me.assets.sprite[obj1].src = o.sprite[obj1];
            }
        }
        me.get = function (tag, name) {
            return assets[tag][name];
        }
    }
});

Assumming that your ajax call is suppose to lazyly initialize other properties of your AssetManager, you need to save the reference of this so that it can be used inside ajax method (where the meaning of this will change)

function AssetManager(path) {

    this.assets = {};

    this.get = function(tag,name) {
        return 0;
    };

    var self = this;

    $.ajax({
        url: path,
        dataType: 'json',
        success: function(o) {
            if (o.sprite) {
                var keys = Object.keys(o.sprite);
                for (var i = 0; i < keys.length; i++) {
                    var obj1 = keys[i];
                    self.assets.sprite[obj1] = new Image();
                    self.assets.sprite[obj1].src = o.sprite[obj1];
                }
            }
            self.get = function (tag, name) {
                return assets[tag][name];
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM