简体   繁体   中英

Javascript Object Jquery callback

In an object I have a method where I want to get some information from a server(JSON format). I want to add this data to my object where the function is (By using a setter). The problem is that this isn't my object but the jquery callback. How could/should I solve this?

function anObject() {

    $.get(URL, doTheCallback); 
    function setExample(example) {    
        this.example = example;
    }

    function doTheCallback(data) {
        this.setExample(data.results[0].example);
    }
}

You can use bind :

$.get(URL,doTheCallback.bind(this));

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Or assign your scope in a variable like:

function anObject() {
    var that = this;

    $.get(URL, doTheCallback); 

    function setExample(example) {    
        that.example = example;
    }

    function doTheCallback(data) {
        that.setExample(data.results[0].example);
    }
}

If you switched to $.ajax , you can use the context option.

function anObject() {
    $.ajax(URL, {context: this}).done(doTheCallback); 
    function setExample(example) {    
        this.example = example;
    }

    function doTheCallback(data) {
        this.setExample(data.results[0].example);
    }
}

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