I'm not sure how to title this question, but here is my dilemma. I have a JS object that I've encapsulated and inherited methods. One of the methods inserts an anchor tag with an onclick event pointing to one of the inhereted methods of the same object. In that second method, I run into trouble because when a user fires the click event of anchor tag, the "this" keyword is now the anchor element. So this prevents me from accessing properties in the object through "this" keyword. Here is my simplified code so you can see what I am talking about.
<!DOCTYPE html>
<html>
<head>
<title>Working out an issue</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
function ListContainerViewer(name, readOnly) {
this.name = name;
this.readOnly = readOnly;
}
ListContainerViewer.prototype = {
constructor: ListContainerViewer,
addListItem: function(itemId, content) {
var removeBtn = $('<a href="#"><span class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></span> </a>')
.clone()
.click(this.removeListItem); // Here, "this" points to ListContainerViewer
removeBtn.appendTo($("#selectedItemList"));
},
removeListItem: function() {
if (this.readOnly == true) { // how do I point to ListContainerViewer.readOnly if this points to <a>?
event.preventDefault();
return;
} else {
this.remove(); // this should point to <a> that has the click event
}
}
}
var listContainer;
$(document).ready(function() {
listContainer = new ListContainerViewer('test', true);
$('#button').click(function() {
listContainer.addListItem('12345', 'test content');
});
});
</script>
</head>
<body>
<h1>Testing OO JS</h1>
<a id='button' href='#'>Click to add</a>
<div id="selectedItemList" style="{width: 800px; height: 400px; background-color: #dddddd}"></div>
</body>
</html>
So if you run this code snippet, click the add link to add the anchor tag, you will notice that when you click the X button anchor, it fires the removeListItem function, this.readOnly is not accessible as this refers to the anchor tag.