I'm trying to do something like this:
var something = "someValue";
some_btn.onPress = function (something) {
someFunction(something);
}
function someFunction (argument) {
trace(argument);
}
But it traces "undefined". What would be the correct way of achieving this?
onPress()
doesn't take arguments.
You could make your own press function like this:
Object.prototype.myPress = function(str:String):Void
{
// Delete old onPress.
if(this["onPress"] != undefined) delete this.onPress;
// Add new onPress.
this.onPress = function():Void
{
someFunction(str);
}
}
With your someFunction()
:
function someFunction(str:String):Void
{
trace(str);
}
And then implement like so:
some_btn.myPress("hello");
This will work:
var something = "someValue";
some_btn.onPress = function () {
someFunction(something);
}
function someFunction (argument) {
trace(argument);
}
Alternatively, this will also work:
var something = "someValue";
some_btn.onPress = function () {
someFunction();
}
function someFunction () {
trace(something);
}
This happens because you named your parameter equals the gloval variable name you've created:
var something = "someValue";
some_btn.onPress = function (something) { ...
This "creates a local variable" with the same name. Since local variables have preference and the onPress don't send any value, you got undefined
.
To solve, remove the variable from the event handler as net.uk.sweet suggested:
some_btn.onPress = function () { ...