我正在努力实现以下目标:
那么,如何从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({});
});
答案 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));
}