I have an observable array that I want to be able to delete entries from via a button in the HTML using the knockout.js framework. However, when I try to use the observable array this.comments in the deleteComment function, I get a TypeError: this.comments is undefined, even though it is clearly defined and has entries. this.comments is even used in the entryComments function which works perfectly fine. Am I missing something?
HTML/PHP:
<div class="textblock">
<h1>User Comments</h1>
<ul id="usercomment" data-bind="foreach: comments">
<li><p><strong data-bind="text: comment"></strong> - <strong data-bind="text: user"></strong></p>
<button data-bind="visible: display(), click: $parent.deleteComment.bind($data, $index)" >Delete Comment</button>
</li>
</ul>
</div>
<br />
<?php if (isset($_SESSION['logged_in'])): ?>
<?php if ($_SESSION['logged_in'] == true): ?>
<div class="textblock">
<ul>
<li>
<form name="commentform" data-bind="submit: enterComment.bind($data,$data.comment )">
<input type="text" data-bind="value: $data.comment"/>
<button type="submit">Submit Comment</button>
</form>
</li>
</ul>
</div>
<?php endif; ?>
<?php endif; ?>
Javascript:
var AppViewModel = function (commentList, userList) {
//Initializing data
this.displayButton = ko.observable(false);
this.comments = ko.observableArray();
this.username;
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
//Giving the array values
for(var i = 0;i<=commentList.length -1;i++ ){
if(username === userList[i]){
this.comments.push(new Comment(commentList[i],userList[i],true ));
}
else{
this.comments.push(new Comment(commentList[i],userList[i], false));
}
};
//Function is called but it cannot define this.comments
this.deleteComment = function(index){
this.comments.splice(index,1);
}
//This function works without any problems
this.enterComment = function (comment) {
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
this.comments.push(new Comment(comment, username,true));
$.post("http://localhost/sem4/recept/AddComment.php", {
comment: comment,
username: username
});
};
//OBJECTS
function Comment(comment, user,bool) {
var self = this;
self.comment = ko.observable(comment);
self.user = ko.observable(user);
self.display = ko.observable(bool);
};
};