Search code examples
javascriptdom-eventsfunction-call

Value not passing correctly to the function onClick


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 ..


Solution

  • function(event, i){ ...
    

    expects i as it's second argument and any i inside its body is unrelated to any i outside 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 always undefined.

    If you do this:

    for(var i=0; i<num; i++){
       var seat = $("...");
       seat.find("...").click(function(e){
         gameDesign.sitOnIndexNo(i)
       )
    }
    

    you access the variable i after its value has changed. You can create a self-invoking function to capture the value of i:

    for(var i=0; i<num; i++){
       var seat = $("...");
       var handler = (function(i){
         return function(event){
           gameDesign.sitOnIndexNo(i)
         )
       })(i);
       seat.find("...").click(handler);
    }
    

    ... or use seat.data, as suggested by @ClarkPan.