简体   繁体   English

Javascript对象Jquery回调

[英]Javascript Object Jquery callback

In an object I have a method where I want to get some information from a server(JSON format). 在一个对象中,我有一个方法,我想从服务器(JSON格式)中获取一些信息。 I want to add this data to my object where the function is (By using a setter). 我想将此数据添加到函数所在的对象中(通过使用setter)。 The problem is that this isn't my object but the jquery callback. 问题是这不是我的对象,而是jquery回调。 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 : 您可以使用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. bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

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. 如果切换到$.ajax ,则可以使用context选项。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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