I’m kinda new on javascript, and I’ve having difficulties (for 2 days now) in implementing the following:
Consider I have an Object(), ‘engine’, which I want it to respond differently according to a post’s content. I.e. there is an action by the user, the engine interprets the action, sends a request to the server, and server responds, and the ‘engine’ acts accordingly.
As a minimal example of the desired behavior, I present an ‘engine’ which hypothetically is receiving mouse click’s position (receiveClickEvent), sends it trough a ‘post’ (requestByAsyncPost), and responds according to its content (respondToRequest):
A small function for doing the post
function requestByAsyncPost(content, funct)
{
/* some initialization missing here to not confuse the reader */
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
funct(xmlhttp.response);
}
}
xmlhttp.open("POST","foobar.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
}
var engine = new Object()
engine.respondToRequest = function(content) {/*implementation*/ }
a small piece of code which I want to be activated when a mouse click occurs (doesn’t matter now how it is triggered)
engine.receiveClickEvent = function(position)
{
var funct = function(content)
{
this.respondToRequest(content); //<<<---- I want to refer engine's 'this'
}
requestByAsyncPost('request=click&position=['+position[0]+','+position[1]+')', funct);
}
This is not working the way I want because the “this” is inside the function funct. How can I implement this kind of behavior?
You must remember outer
thisby this way or other. Like: