I am quite newbie in OOP. I have lots of ajax calls and i want to combine them as an object.
Here is my function;
var Ajax_call = function(target) {
this.target = target;
this.data = function(){
return $("#"+this.target+"").parent("form").serialize();
};
this.start = function(){
status(true);
var data = this.data();
$.ajax({
type : "post",
url : $("#"+this.target+"").attr('action'),
data : data + '&ajax=' + 1,
dataType : "json",
timeout : 3000,
success :
function(serv){
if(serv.error){
this.denied(); ///// TypeError: undefined is not a function
}
if(serv.done){
//this.succeed();
}
},
error :
function(x,t,m){
//this.failed();
}
});
};
};
I want to define denied() method here;
$('body').on('click','#register_submit',function(event){
event.preventDefault();
Ajax_call.denied = function() {
console.log (serv.error);
};
var register = new Ajax_call((this.id));
register.start();
});
Thanks!
HERE IS THE SOLUTION;
I defined duplicated variable this
to _this
. So when js overload on it i can use _this
instead of this
. There is no need for prototype.
Declaration;
var Ajax_call = function(target) {
this.target = target;
this.data = function(){
return $("#"+this.target+"").parent("form").serialize();
};
this.denied;
this.start = function(){
var _this = this; /// Js overload on this.
}
Ajax part;
$.ajax({
type : "post",
url : $("#"+this.target+"").attr('action'),
data : data + '&ajax=' + 1,
dataType : "json",
timeout : 3000,
success :
function(serv){
if(serv.error){
_this.denied(serv); ///// Fixed
}
if(serv.done){
//_this.succeed();
}
},
error :
function(x,t,m){
//_this.failed();
}
});
Usage;
$('body').on('click','#register_submit',function(event){
event.preventDefault();
var register = new Ajax_call((this.id));
register.denied = function(serv) {
console.log (serv.error);
};
register.start();
});