Reputation: 485
Getting issue in binding the ko observableArray to table. [jsFiddle][1].
http://jsfiddle.net/chetanpawar0989/do6o7wtb/
<tbody data-bind="foreach: $root.TakenCourses">
<tr>
<td> <span data-bind="text: courseName"></span></td>
<td> <span data-bind="text: courseCredits"></span></td>
<td> <button data-bind="click: removeCourse">Remove</button></td>
</tr>
</tbody>
On jsFiddle it's just showing first item. However when I add the course, the length of array is increasing and the latest courses are getting added to takenCourses array (can be seen in alert box) That means I am goofing up something in binding the data.
Also when i run the same code in my webpage, it shows the first course repeatedly when I add the course.
The remove functionality is not working too.
I am new to KO and learning the basics.
Upvotes: 2
Views: 1182
Reputation: 26730
The problem is that there is no function removeCourse
in the course
objects.
<button data-bind="click: removeCourse">Remove</button>
should therefore be
<button data-bind="click: $root.removeCourse">Remove</button>
You might though want to redesign everything slightly, maybe like this:
var course = function(name, credits, selected) {
var self = this;
this.courseName = name;
this.courseCredits = credits;
this.selected = ko.observable(!!selected);
this.unselectCourse = function() {
self.selected(false);
};
};
Instead of maintaining lists of selected and unselected courses, I would advise to make this a property of each course. In the view model, you would then use dynamic lists:
function NCSUCourseModel()
{
var self = this;
//Static list of available courses
self.courses = ko.observableArray([
new course("Orientation", 1, true),
new course("Operating Sytems", 3),
new course("Algorithms", 3),
// ...
]);
self.selectedCourse = ko.observable();
self.AvailableCourses = ko.computed(function() {
return ko.utils.arrayFilter(self.courses(), function(item) {
return item.selected() == false;
});
});
self.TakenCourses = ko.computed(function() {
return ko.utils.arrayFilter(self.courses(), function(item) {
return item.selected() == true;
});
});
self.AddCourse = function() {
this.selectedCourse().selected(true);
};
}
http://jsfiddle.net/do6o7wtb/2/
Upvotes: 1