Mootools calling class method onSuccess Ajax
I'm trying to achieve the following:
- User clicks on an element and the cmove function is invoked (works)
- cmove passes an JS object to the ajax method (works)
- ajax method submits the object to the move/test controller (PHP/CodeIgniter) (works)
- controller returns some JSON Data (works)
- onSucces calls the move method to do some stuff (no chance calling that method)
So, how can I call the move method out of the onSuccess? And is there a better way of pushing the moveObj around?
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(开发者_如何学CresponseText); // 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({});
});
you need to bind the callback function for the Request instance to the scope of your class or save a reference of your class' instance (self = this
) and call via that instead:
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));
}
精彩评论