0

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);
    }
}

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Does the second one* work with prototype too? I get an refference error when I use prototype: ReferenceError: that is not defined
1

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.