...

View Full Version : Assigning Onclick Object Function to Field from Within Object



rsomma
03-04-2009, 02:37 PM
I've been playing with this one since yesterday. I have an object that I'm instantiating, and, within the initialization of the object, I'm assigning one of the object's functions an onclick event to a field on the page.

I've tried everything I can think of. Using "this." doesn't work, sending the object name through with a variety of different methods of calling it don't work. I'm guessing there's a pretty straightforward and easy solution to this that I'm just not considering.

I've commented out all the different strategies in the code below. Thanks to everyone in advance for the help.



<html>
<body>

<form name="test">
<input type="button" id="testButton" value="TEST">
</form>

<script language="javascript">

function DoSomething()
{
this.fieldToAssignOnchange = '';
}

DoSomething.prototype =
{
initialize : function(field,objectName)
{
this.fieldToAssignOnchange = document.getElementById(field);
this.functionCallToString = objectName + ".successMessage();";
this.fieldToAssignOnchange.onclick = function()
{
//THIS FAILS
//objectName.successMessage();

//THIS FAILS
//this.successMessage();

//THIS WORKS - BUT I CAN'T HARDCODE THE VALUE
//alertButton.successMessage();

//THIS DOES NOTHING
//this.functionCallToString;

//THIS DOES NOTHING
//eval(this.functionCallToString);
};
},
successMessage : function()
{
alert("Success!");
}
}

var alertButton = new DoSomething;
alertButton.initialize("testButton","alertButton");

</script>

</body>
</html>

rsomma
03-04-2009, 07:26 PM
That should read, "I'm assigning one of the object's functions as an onclick event to a field on the page."

Apologies for any confusion.

shyam
03-04-2009, 07:56 PM
use a closure ;)


DoSomething.prototype = {
initialize : function(field,objectName) {
this.fieldToAssignOnchange = document.getElementById(field);
var thisObj = this;
this.fieldToAssignOnchange.onclick = function() {
thisObj.successMessage();
};
},
successMessage : function() {
alert("Success!");
}
}

rsomma
03-04-2009, 09:12 PM
Thanks so much! I'm new to closures, and didn't fully understand the articles I was coming across on them. You have been a big help!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum