KnockoutJS를 사용하고 있는데 observableArray의 관찰 가능 객체가 부모에게 변경 사실을 알릴 수있는 방법을 알고 싶습니다.변경 사항을 부모에게 알리는 방법
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>
자바 스크립트 예를 들면 다음과 같습니다 위의 예에서
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;
});
});
, 내가 선택한 필드의 수와 제목을 표시합니다. observableArray
에 대해 subscribe
이벤트가 있지만 배열에서 항목을 추가하거나 제거 할 때만 발생하므로 사용자가 필드 목록의 체크 박스를 실제로 검사 할 때 이벤트가 시작되지 않습니다. 이를 달성하는 한 가지 방법은 확인란에 onchange 이벤트를 추가하여 부모에서 메서드를 호출하는 것입니다.이 메서드는 header
개체의 childrenCount
을 업데이트하는 외부 메서드를 호출합니다. 이 작업을 수행하는 더 좋은 방법이 있습니까?
아쉽게도 내 응용 프로그램에서 설계된 방식대로 applyBindings를 별도로 유지해야합니다. 그래서 배열 내의 obserbale 객체의 값이 업데이트 될 때마다 외부 함수를 호출 할 방법이 필요합니다. 단추에 대한 클릭 핸들러의 경우,이 예제는 내 실제 프로젝트가 아닙니다. – Wiz