I have object with validate property and that property function send request to server to test.
//clsAjax.js file where i access request function
request: function(cmd, callback){
_sendReq(cmd, callback);
}
//Definition
obj = {
title : 'name',
validation : function(this){
this.valid = false;
clsAjax.request('duplicate', function(){
if(response == true){
this.valid = true;
console.log(this.valid);
}
});
}
}
//function call
form.validation(obj);
console.log(obj.valid); // It always have false value
validation function receive true but before that it executed validation false line.
I want it to wait till ajax finish execution.
How to do that??
Thank.
答案 0 :(得分:0)
Two problems in your code.
this
generally refers to object to which a function was assignedSo if you do this:
var obj = {num: 1234, func: function() {console.log(this);}};
obj.func();
You get this output:
And it works same with your function:
clsAjax.request('duplicate', function(){...});
There are two workarounds:
Create reference to this
before creating the callback:
var _this = this;
clsAjax.request('duplicate', function(){_this.valid = true;});
Use HTML5 Function.prototype.bind
- that changes meaning of this
in a function:
var callback = function(){this.valid = true;}.bind(this);
clsAjax.request('duplicate', callback);
form.validation(obj);
console.log(obj.valid); // It always have false value
When you do console.log(obj.valid)
your callback wasn't called yet because it's still communicating with the server.