I want to call an internal function once an ajax call back function is activated. Because there is a delay I want to know if my local variables will still be correct when it is called, particularly this.response_element as it is used by the call back function.
The callback function is initiated when ajax status == 200
var ControlSignIn = function( )
{
this.form_element = document.getElementById( 'signin' ),
this.response_element = document.getElementById( 'signin_response' ),
this.text_object = new Text( this.form_element ),
this.message_object = new Message( this.response_element );
};
ControlSignIn.interface = function()
{
new ControlSignIn().invoke();
};
ControlSignIn.prototype.invoke = function( )
{
if( CONSTANT.VALIDATE_ON === 1 )
{
if( !this.text_object.checkEmpty() )
{
this.message_object.display( 'empty' );
return false;
}
if( !this.text_object.checkPattern( 'email' ) )
{
this.message_object.display( 'email' );
return false;
}
if( !this.text_object.checkPattern( 'pass' ) )
{
this.message_object.display( 'pass' );
return false;
}
}
/* new internal call_back */
AjaxNew.use( ajaxSerialize( this.form_element ) + '&ajax_type=ControlSignIn', ControlSignIn.invoke.callBack );
function callBack( server_response_text )
{
ajaxType( server_response_text, this.response_element, 'respond' );
}
/* Removed
Ajax.repeatUse( ajaxSerialize( this.form_element ) + '&ajax_type=ControlSignIn', ajaxTypeRespond, this.response_element );
*/
};
Solution:
AjaxNew.use( ajaxSerialize( this.form_element ) + '&ajax_type=ControlSignIn', ControlSignIn.invoke.callBack );
var response_element = this.response_element;
function callBack( server_response_text )
{
ajaxType( server_response_text, response_element, 'respond' );
}
No, it won't. Eventhough the property may be intact, this
won't point to the object.
Copy the value to a local variable, and use a function literal, then the local variable will be catched in the closure for the function and kept intact and accessible:
var element = this.response_element;
AjaxNew.use(
ajaxSerialize(this.form_element) + '&ajax_type=ControlSignIn',
function(server_response_text) {
ajaxType(server_response_text, element, 'respond');
});
The answer is yes and no. Yes, local variables will still be around, but the this
reference is always reset on every function call. Thus the callback will have its own this
value.
The solution is to leverage the "yes" part of the answer and save your this
reference in another variable. Then you use that variable (instead of this
) in the callback.
Now, that said, the structure of your code confuses me a little and I can't exactly tell how your "callback" is supposed to work; that is, it references this
but I don't see how it expects it to be set.
someFunction.call( what_this_should_be, arg, arg ...)
Pointy 2012-04-03 21:02