I am using KnockoutJS and I would like to know of a way where a observable object in an observableArray can notify the parent of a change. Here is an example:
http://jsfiddle.net/paragnair/CEEZ5/
HTML:
<h1 id="heading"> <text data-bind="text:childrenCount"></text> Fields selected</h1>
<table id="form">
<tbody data-bind="foreach:children">
<tr>
<td data-bind="text:name"></td>
<td><input type="checkbox" data-bind="checked:isSelected"/></td>
</tr>
</tbody>
</table>
<a href="#" id="btn-add">Add More Fields</a>
Javascript:
var Child = function(name) {
var self = this;
self.name = ko.observable(name);
self.isSelected = ko.observable(false);
},
Parent = function() {
var self = this;
self.children = ko.observableArray([
new Child('One'),
new Child('Two'),
new Child('Three')
]);
self.children.subscribe(function(children) {
header.childrenCount($.map(children, function(a) {
return a.isSelected() ? 1 : null;
}).length);
});
},
header = {
childrenCount: ko.observable(0)
};
var parentModel = new Parent(),
extra = parentModel.children().length;
ko.applyBindings(parentModel, $('#form')[0]);
ko.applyBindings(header, $('#heading')[0]);
function setHeading(childrenCount) {
header.childrenCount(childrenCount);
}
$(document).ready(function() {
$('#btn-add').click(function() {
extra++;
parentModel.children.push(new Child('Extra ' + extra));
return false;
});
});
In the above example, I want to show the heading with the number of fields selected. I have a subscribe
event for the observableArray
but that only fires when something is added or removed from the array so when the user actually checks a checkbox in the fields list, the event is not fired. One way of achieving this is by adding a onchange event on the checkbox to call a method on parent which inturn calls some external method which updates the childrenCount
on the header
object. Is there a better way of doing this?