Mootools调用类方法onSuccess Ajax

时间:2011-04-11 19:43:23

标签: ajax mootools

我正在努力实现以下目标:

  1. 用户点击元素并调用cmove函数(有效)
  2. cmove将JS对象传递给ajax方法(正常)
  3. ajax方法将对象提交给移动/测试控制器(PHP / CodeIgniter)(正常工作)
  4. controller返回一些JSON数据(工作)
  5. onSucces调用move方法做一些事情(没有机会调用该方法)
  6. 那么,如何从onSuccess中调用move方法?是否有更好的方法推动moveObj?

    var Plane = new Class({
        Implements: Options,
    
        options: {
            action: null
        },
    
        initialize: function(options) {
            this.setOptions(options);
            $('somelement').addEvent('click', this.cmove.bind(this));
        },
    
    
        cmove: function(event, action) {
    
            moveObj = new Object();
            moveObj.x = 123;            
    
            this.ajax('cmove', moveObj);
    
        },
        move: function(moveObj) {
            console.log("Yippe!");  // not getting here :(              
        },      
    
        ajax: function(action, obj) {
    
            resp = $('resp');
    
            var myRequest = new Request.JSON({
                url: '<?php echo site_url('move/test'); ?>',
                method: 'get',
                onRequest: function(){
                    resp.set('text', 'wait...');
                },
    
                onSuccess: function(responseText){
    
                    switch(action)
                    {
                    case 'cmove':
    
                        test3.move(responseText); // not working
                        this.move(responseText);  // not working
                        parent.move(responseText);  // not working
    
                        resp.set('text', responseText.x);
                        break;              
    
    
                },
                onFailure: function(){
                    resp.set('text', 'Sorry, your request failed :(');
                }
            }).send('coords='+ JSON.encode(obj));           
    
        }
    
    });
    
    
    window.addEvent('domready', function(){
        var test3= new Plane({});
    });
    

1 个答案:

答案 0 :(得分:4)

您需要将Request实例的回调函数绑定到类的范围,或者保存类实例(self = this)的引用并通过它调用:

ajax: function(action, obj) {

    var self = this; // save a refrence
    var resp = document.id("resp");

    new Request.JSON({
        url: '<?php echo site_url('move/test'); ?>',
        method: 'get',
        onRequest: function(){
            resp.set('text', 'wait...');
        },

        onSuccess: function(responseText){

            switch(action) {
                case 'cmove':

                    self.move(responseText); // will work
                    this.move(responseText);  // will also work

                break;              
            }

        }.bind(this), // binding callback to instance so this.method works
        onFailure: function(){
            resp.set('text', 'Sorry, your request failed :(');
        }
    }).send('coords='+ JSON.encode(obj));           

}