类中的Javascript回调失去绑定

时间:2012-06-29 11:01:39

标签: javascript callback mootools

我的类有一个问题,我设置了一个回调函数,在ajax请求之后触发,除了回调然后有this = window而不是this =调用类,这个工作正常。我试图摆弄绑定等无济于事。任何帮助表示感谢。

<?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();

2 个答案:

答案 0 :(得分:1)

this永远不是函数的继承范围(即闭包)的一部分,而是在调用函数时确定,在本例中由onS(object)确定。这样称呼,功能就是 - 一个功能。您需要致电this.onS(object),但由于onSuccess功能无法了解this,因此无法解决此问题。

要将最外面的对象作为this调用foo / onS函数,您必须在另一个变量中保存对它的引用,通常称为that

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

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

答案 1 :(得分:-1)

更改此

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

到:

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