[英]Knockout custom binding not updating
請檢查我在做什么錯。
當我在javascript中創建控件時,自定義bindinghandler的update部分不執行。 我有一個添加函數,可以在表中創建一行。 綁定到自定義綁定的控件會執行更新部分,但不會執行隨后添加的控件。
的HTML
<div id="collapse-programHead" class="panel-collapse collapse">
<div class="panel-body">
<table class="cv">
<thead>
<tr>
<th>Programme</th>
<th>Core Module Count</th>
<th>Core SAQA Credit</th>
<th>Elective Module Count</th>
<th>Elective SAQA Credit</th>
<th>Credit</th>
</tr>
</thead>
<tbody data-bind="foreach: ProgrammeHead">
<!-- ko if: isActive -->
<tr>
<td><select data-bind="options: programmes, optionsText: 'Programme', value: ProgrammeID, optionsValue:'ProgrammeID', optionsCaption:''"></select></td>
<td><input type="text" readonly="true" data-bind="value:ModuleCount, offeringCount:$root.programmeOfferingCount"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text" data-bind="value: Credit"/></td>
<td class="tinyTD"><a class="removeRow" id="ProgrammeHead" title="Delete item" href="javascript:void(0)"></a></td>
<td class="hideTD"><input type="hidden" data-bind="value: CVId" /></td>
<td class="hideTD"><input type="hidden" data-bind="value: ProgrammeID" /></td>
<td class="hideTD"><input type="hidden" data-bind="value: ProgrammeOfferingID" /></td>
<td class="hideTD"><input type="hidden" data-bind="value: ManagementLoadID" /></td>
</tr>
<!-- /ko -->
</tbody>
</table>
<a title="Add row" id="a2" href="javascript:void(0)" data-bind="click: addRow.bind($data, 'programHead')"><label>Add row</label></a>
</div>
</div>
ko.bandingHandler
ko.bindingHandlers.offeringCount = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
return { controlsDescendantBindings: true };
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.unwrap(valueAccessor)
var id = ko.unwrap(bindingContext.$data.ProgrammeID);
var item = programmes().filter(function (i) {
return i.ProgrammeID() == id;
})
if (item.length > 0) {
var count = ko.unwrap(item[0].ProgrammeOfferingCount);
bindingContext.$data.ModuleCount(count);
}
}
};
ProgrammeHead添加
self.ProgrammeHead.push({ 'ManagementLoadID': '', 'CVId': '', 'ModuleCount': count, 'ProgrammeID': '', 'ProgrammeOfferingID': '', 'Credit': '', 'isActive': active });
valueAccessor
參數是一個返回綁定值的函數。 如果綁定值是可觀察值,則還必須“解包”該可觀察值以獲取實際值。 在您的代碼中,您沒有正確解開該值。 它應該是:
var value = ko.unwrap(valueAccessor());
update
函數的內容充當ko.computed
的主體,因此就像計算的依賴項跟蹤一樣起作用:
因此,Knockout不僅在評估程序第一次運行時就檢測到依賴關系,而且每次都會重新檢測它們。 例如,這意味着依賴關系可以動態變化:依賴關系A可以確定計算的可觀察值是否還依賴於B或C。然后,僅當A或您當前選擇的B或C更改時,它才會重新評估。 您不必聲明依賴關系:它們是在運行時由代碼的執行確定的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.