简体   繁体   中英

Javascript callback within class loses binding

I have a problem with my class where I set a callback function to fire after an ajax request, this works fine except for the callback then having this= window instead of this = the calling class. I have tried fiddling with the bindings etc to no avail. any help appreciated.

<?php
if (isset($_POST['id'])){
    echo json_encode(array('key' => 'val'));
    die;
}
?>
<script type="text/javascript" src="/linkup/js/mootools-core-1.4.3-full-compat-yc.js" charset="utf-8"></script>
    <script type="text/javascript" src="/linkup/js/mootools-more-1.4.0.1.js" charset="utf-8"></script><script>
var myClass = new Class({
    blah: function(){
        console.log('this worked ok');
    },
    foo: function(){
        this.blah(); // at this point it is failing with "unknown function"
    },
    bar: function(){
        this.reqJSON({id:1,req:'grabpoints'},this.foo);
    },
    // data - an aray containing some data to post {id:1,req:'grabpoints'}
    // onS - a function to fire on return of data
    reqJSON: function(data,onS){
        if (this.jsonRequest) this.jsonRequest.cancel();
        this.jsonRequest = new Request.JSON({
                url: 'test.php',
                onRequest: function (object){
                    console.log('sending json');
                },
                onSuccess: function (object){
                    console.log('json success');
                    onS(object);
                }
            }
        ).post(data);
    },

});
var o = new myClass();
o.bar();

this is never part of an inherited scope (ie the closure) for a function, but instead determined when the function is called, in this case by onS(object) . Called this way, the function is just that - a function. You need to call this.onS(object) , but this won't work in your case because the onSuccess function does not know about this either.

To call the foo/onS function with the outermost object as this you must save a reference to it in another variable, commonly called that :

reqJSON: function(data,onS){
    var that = this;
    ...

    onSuccess: function (object){
        console.log('json success');
        that.onS(object);
    }

change this

bar: function(){
    this.reqJSON({id:1,req:'grabpoints'},this.foo);
}

to :

bar: function(){
  var self = this;
  this.reqJSON({id:1,req:'grabpoints'},self.foo);
}

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