0

first of all, sorry for my bad english :( I have a function, that function shuffle the cards i have and creates the DIVS with the images I need to have one event for all these divs my code is:

//shuffles the cards
    function newBoard(){
        tiles_flipped = 0;
        var output = '';
        memory_array.memory_tile_shuffle();
        for(var i = 0; i < memory_array.length; i++){
            //output += '<div class="container" id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
            var img = memory_array[i];
            var tile = 'tile_' +i
            var div = document.createElement('div');
            div.className='container';
            div.id=tile;
            div.addEventListener('click',function(){
                memoryFlipTile(tile,img)},false);
            document.getElementById('memory_board').appendChild(div);
        }
        //document.getElementById('memory_board').innerHTML = output;
    }

    function score(){

        var level = $('.level').text();
        puntuacion = puntuacion + (10 * level);
        $('.score').text(puntuacion);
    }
    //compare cards
    function memoryFlipTile(tile,val){


    if(tile.innerHTML == "" && memory_values.length < 2){
        tile.style.backgroundImage = "url('bagels/"+val+"')"
        if(memory_values.length == 0){

            memory_values.push(val);
            memory_tile_ids.push(tile.id);
        } else if(memory_values.length == 1){
            memory_values.push(val);
            memory_tile_ids.push(tile.id);
            if(memory_values[0] == memory_values[1]){
                for(var j = 0; j<memory_tile_ids;j++ ){
                    alert($('#' + memory_tile_ids[j]));
                    $('#' + memory_tile_ids[j]).unbind('click');
                }
                score();
                tiles_flipped += 2;
                // Vaciamos los 2 arrays
                memory_values = [];
                memory_tile_ids = [];
                // Comprobamos que todas las cartas se han girado correntamente y empezamos un nuevo nivel
                if(tiles_flipped == memory_array.length){
                    /*document.getElementById('memory_board').innerHTML = "";
                    newBoard();*/
                }
            } else {
                function flip2Back(){
                    // Flip the 2 tiles back over
                    var tile_1 = document.getElementById(memory_tile_ids[0]);
                    var tile_2 = document.getElementById(memory_tile_ids[1]);
                    tile_1.style.background = 'url(carta.png) no-repeat';
                    tile_2.style.background = 'url(carta.png) no-repeat';
                    // Clear both arrays
                    memory_values = [];
                    memory_tile_ids = [];
                }
                setTimeout(flip2Back, 500);
            }
        }
    }
}

I solved it using the following jQuery code

memory_array.memory_tile_shuffle();

    var $board = $('#memory_board');


    $.each(memory_array, function(i, v) {
        var id = 'tile_' + i;
        var card_tpl = '<div class="container" id="'+id +'"></div>';
        $(card_tpl)
            .on('click', function() {
                memoryFlipTile(this, memory_array[i]);
            })
            .attr('id', id).appendTo($board);
    });
    var $board = $('#memory_board');


    $.each(memory_array, function(i, v) {
        var id = 'tile_' + i;
        var card_tpl = '<div class="container" id="'+id +'"></div>';
        $(card_tpl)
            .on('click', function() {
                memoryFlipTile(this, memory_array[i]);
            })
            .attr('id', id).appendTo($board);
    });

Here its the app: http://juego.adrianpyjavierr.hol.es/juego.html

2 Answers2

1

You need to use a IIFE that returns a function parameterized for your tile and img at each loop iteration. Specifically change:

div.addEventListener('click',function(){
            memoryFlipTile(tile,img)},false);

by:

div.addEventListener('click',(function(ti,im){
        return memoryFlipTile(ti,im);
})(tile,img),false);

For more information, a good post on IIFEs here:

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Best.

E. Valencia
  • 447
  • 2
  • 6
  • thanks for the answer, but i replace the code and the inspector returns 2 errors div.addEventListener('click',(function(ti,im){ function(){ <---- unexpected token ) return memoryFlipTile(ti,im); } })(tile,img),false); – Adrian Palomera Apr 24 '14 at 14:07
  • You are right, I got the syntax wrong. I corrected the code and edited the answer. Let's hope it is right now! – E. Valencia Apr 24 '14 at 14:16
  • I checked your game and now it seems to work! Did my code work for you? If my answer was helpful, please consider to accept it. – E. Valencia Apr 24 '14 at 14:41
  • 1
    your code works fine!! finally i found the answer using jQuery .on, but your code works!! thanks for all! – Adrian Palomera Apr 24 '14 at 15:30
0

You can use .live, a jQuery event that 'Attach an event handler for all elements which match the current selector, now and in the future.'

This the jQuery official API Documentation: https://api.jquery.com/live/