gameDesign = {
makeSeats: function( num ) { //num = number of seats
var seats = [];
var seat;
var seatWidth = 20;
var seatHeight = 20;
var total = 100;
for( var i=1; i<= num; i++ ) {
seat = $('<div id="seat_'+i+'" class="seats"><div id="index_'+i+'" style="height:100%; width:100%;"><div style="height:100%; width:100%;">Sit Here</div></div></div>');
seat.children(":first").children(":first").click( function(event, i){
var tim = i;
gameDesign.sitOnIndexNo( tim ); });
},
sitOnIndexNo: function( seatIndex ) {
tableFunc.makePlayerSit( RummyGlobal.myInfo.get_jid(), seatIndex );
}
}
Problem: On clicking "Sit Here" index value is being passed as undefined .. I know this is something related to closures .. but, I need further explanation and solution ..
expects
ias it’s second argument and anyiinside its body is unrelated to anyioutside its body.jQuery passes only one argument to an event handler it calls – the event. Additionaly, it passes the target element as
this. This means that the second argument is alwaysundefined.If you do this:
you access the variable i after its value has changed. You can create a self-invoking function to capture the value of i:
… or use
seat.data, as suggested by @ClarkPan.