long time lurker here in need of help.
I have a class named button
class GameButton
{
constructor ( id, width, height, buttonFunction, attrs )
{
this._id = id
this._width = width;
this._height = height;
this._attrs = attrs;
this._buttonFunction = buttonFunction
}
append()
{
$( '#gameContainer' ).append( '<img id="' + this._id + '" src="">');
$( '#' + this._id ).css( 'top', this._top + '%' );
$( '#' + this._id ).css( 'left', this._left + '%' );
$( '#' + this._id ).on( 'click', this._buttonFunction );
}
}
It has more attributes but whatever. When I create instances of this class they work fine as long as no parameters are needed. I am lost here and some help will save my life
let startGame = function( language )
{
some awesome code here
}
let buttonStart = new GameButton( 'start', 43, 0, startGame, 'myParamValue' );
Thanks in advance
I tried this
by doing the following
$( '#' + this._id ).bind( 'click', this._attrs, this._buttonFunction );
but doesn’t work
2
Answers
You had the right approach with the
bind
method that you mentioned.Perhaps you didn’t pick the value correctly in the passed function, since the params get bound to the
event object
and are not passed as stand-alone.This means you will be able to locate the params under
event.data
.I have created a sample runnable code that uses your question code as base and assuming everything else is working as intended to highlight the bind and param passing functionality.
Once you click on the image, the passed param is displayed below the image in the designated container.
You can use .on() to bind click event on parent container