I have a Javascript script in which I define a class called a "Layer". I put code in the Layer
constructor, so that each time a new Layer
object is created a checkbox associated with that layer is added to the HTML document. I also created a JQuery event handler within the constructor so that when the new checkbox is clicked, the layer is either shown or hidden within the document depending on the state of the checkbox. For some reason however, the event handler only works for the most recently created layer. Somehow the old event handlers are getting overwritten. I searched on here for similar questions, and saw that using the on
function from JQuery rather than click
is the way to go, but I'm still having the same issue. Here's my code...
Layer2D.prototype.addToUI = function() {
if (this.firstLayer()) {
var layerDiv = document.createElement('div');
layerDiv.className = 'content';
layerDiv.id = 'layerNames';
}
else {
var layerDiv = document.getElementById('layerNames');
}
layerDiv.innerHTML += '</br>' +
'<div class="ui toggle mini checkbox" id="layer' + this.name +'">' +
'<input type="checkbox" name="' + this.name + '" checked>' +
'</input>' +
'<label>' + this.name + '</label>' +
'</div>';
if (this.firstLayer()) {
var parentDiv = document.getElementById('layerMenu');
parentDiv.appendChild(layerDiv);
};
$('#layer' + this.name).after('<br/>');
var This = this;
$('#layer' + this.name).on('click', ':input', function(e) {
checked = $(this).is(':checked');
console.log(This);
if (checked === true) {
This.show();
}
else {
This.hide();
}
});
};