Can someone explain why this code works:
$('#FonykerUsernameRegister').blur(function(){
if($(this).val().length > 2) {
$.ajax({
url: '<?php echo $html->url('/fonykers/validate_username',true); ?>' + '/' + $(this).val(),
dataType: 'json',
type: 'POST',
success: function(response) {
if(!response.ok) {
$('#FonykerUsernameRegister').addClass('error');
error.html(response.msg);
error.fadeIn();
} else {
if($('#FonykerUsernameRegister').is('.error')) {
$('#FonykerUsernameRegister').removeClass('error');
}
$('#FonykerUsernameRegister').addClass('ok');
}
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
} else {
error.html('Username must have at least 3 characters');
error.fadeIn();
$('#FonykerUsernameRegister').addClass('error');
}
});
As opposed to this one:
$('#FonykerUsernameRegister').blur(function(){
if($(this).val().length > 2) {
$.ajax({
url: '<?php echo $html->url('/fonykers/validate_username',true); ?>' + '/' + $(this).val(),
dataType: 'json',
type: 'POST',
success: function(response) {
if(!response.ok) {
$(this).addClass('error');
error.html(response.msg);
error.fadeIn();
} else {
if($(this).is('.error')) {
$(this).removeClass('error');
}
$(this).addClass('ok');
}
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
} else {
error.html('Username must have at least 3 characters');
error.fadeIn();
$(this).addClass('error');
}
});
I’m assuming the second one is a bit more optimized so I’d rather use that way if possible, but it just isn’t setting the classes on the elements.
The first code (working code) refers to the element by id: the jQuery
$function is basically a replacement fordocument.getElementById.In the second code, when you try to reference the element using
this, the scope is such thatthiswill likely refer to the request object orwindow. The solution, if you want to use thethisobject with the scope you desire, is to use theproxymethod to bind the handler function, or grab the target element as a variable to use in a closure.Of the two methods, using
proxyis the the least likely to end up causing a circular reference. The code you’ve given here is safe, but you really have to watch yourself when you use element references in closures if the target element will be removed from DOM at some point – you’d then potentially have a situation where the browser’s garbage collector cannot free the resources related to the element because the closure is holding open a reference pointer.All
proxydoes is to create a closure with the specified scope, see the docs here.For further reading on scope, check out this MDC document and this MDC scope “cheat sheet”
Closure:
Proxy