Search code examples
javascriptclone

javascript clone node reattach event listeners


I have used a cloneNode to save and restore a Sudoku table. However when I clone it and then restore the table, the restored version is no longer editable.

//Create Save Function and store in a cloneNode
function Save(){
var table = document.getElementById("sudoku");
clone = table.cloneNode(true);  
}
//Create Restore Function and restore saved state from the cloneNode and delete parent table
function Restore(){
var table = document.getElementById("sudoku"),
parent = table.parentNode;
parent.removeChild(table);
parent.appendChild(clone);
}

Here are my event handlers

function selectCell() {
if (current_cell !== null) {
    current_cell.className = 'tofill';
}
current_cell = this;
current_cell.className = 'selected';
 }

// Capture keyboard key presses. If the key pressed is a digit
// then add it to the current cell. If it is a space then empty
// the current cell.
function keyPress(evt) {
if (current_cell == null)
    return;
var key;
if (evt)
    // firefox or chrome
    key = String.fromCharCode(evt.charCode);
else
    // IE
    key = String.fromCharCode(event.keyCode);
if (key == ' ')
    current_cell.innerHTML = '';
else if (key >= '1' && key <= '9')
    current_cell.innerHTML = key;
  }

How do I reattach the event listeners so the table remains editable when it is restored after being saved.

EDIT

 var current_cell = null; // the currently selected cell
 var saved = {};        // Object for saving the current game
 function initialize() {
var col, row;
// Work through all the cells in the table and set
// onclick event handlers and classNames for the empty
// ones.
for (row = 0; row <=8; row++) {
    for (col=0; col <= 8; col++) {
        var cell = document.getElementById('cell_' + col + '_' + row);
        if (!parseInt(cell.innerHTML)) {
            // cell is empty
            cell.onclick = selectCell;
            cell.className = 'tofill';
        }
    }
}
document.onkeypress = keyPress;
save();
    }

This is how I attach the event handlers but when I reattach in the same way I still have the same problem


Solution

  • var current_cell = null; // the currently selected cell
    var saved = {};        // Object for saving the current game
    function initialize() {
    var col, row;
    // Work through all the cells in the table and set
    // onclick event handlers and classNames for the empty
    // ones.
    for (row = 0; row <=8; row++) {
    for (col=0; col <= 8; col++) {
        var cell = document.getElementById('cell_' + col + '_' + row);
        if (!parseInt(cell.innerHTML)) {
            // cell is empty
            cell.onclick = selectCell;
            cell.className = 'tofill';
        }
      }
    }
    document.onkeypress = keyPress;
    save();
    }
    

    Just reinserted this code into the resotre function to reattach event listeners