问题描述
为什么我不能对某些表格标签中的按钮进行点击绑定?如果我将按钮移到表格外它会起作用吗?
<td>
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
</td>
虚拟机:
define(['viewmodels/shell','durandal/services/logger','plugins/dialog','viewmodels/shell','toastr','knockout','kovalidationconfig','plugins/router','typeahead.bundle'],function (shell,logger,dialog,shell,toastr,ko,kvc,router,typeahead) {
var vm = {
activate: activate,shell: shell,data: ko.observableArray([]),close: function () {
$(window).off('popstate',vm.goBack);
$(window).off('resize',adjustModalPosition);
dialog.close(vm,'cancel');
},goBack: function () {
$(window).off('popstate','back');
},editPreregisteredChildren: function () {
router.navigate("#/function/" + this.id);
},incrementClickCounter : function() {
var prevIoUsCount = this.numberOfClicks();
this.numberOfClicks(prevIoUsCount + 1);
}
currentPage: ko.observable(1),itemsPerPage: ko.observable(10),hasNextPage: ko.observable(false),prevIoUsPage: prevIoUsPage,nextPage: nextPage,searchCriteria: ko.observable(''),applySearch: applySearch,locations: ko.observableArray([]),locationId: ko.observable(),LocationName: ko.observable(),exportHref: ko.observable("/spa/ExportSchedulings"),bindingComplete: function (view) {
bindFindLocationEvent(view);
}
};
...
)};
解决方法
您是否可能处于嵌套状态?当我绑定到具有多个视图模型的视图时,我有时会遇到这个问题。尝试将 data-bind='with: nameOfTheViewModel' 添加到表数据标记:EG:
<td data-bind='with: nameOfTheViewModel'>
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
</td>
您可能还需要附加 $Parent。 data-bind='with: $Parent.nameOfTheViewModel'
,您的表的主体可能会遍历一个数组,并且每一行都代表数组项,而不是根虚拟机。您需要绑定到“click: $parent.incrementClickCounter”或“click: $root.incrementClickCounter”。