knockout.jsknockout-mvc

knockout.js in MVC - not working binding in html table


why I cant do click binding for button in tags of some table? if I move button outside the table it works?

<td>
    <div>
        You've clicked <span data-bind="text: numberOfClicks"></span> times
        <button data-bind="click: incrementClickCounter">Click me</button>
    </div>
                                  
</td>

vm:

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', vm.goBack);
                $(window).off('resize', adjustModalPosition);
                dialog.close(vm, '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);
            }
        };
...
)};

Solution

  • You table's body is likely iterating over an array, and each row is representing the array item, not the root vm. You need to bind to "click: $parent.incrementClickCounter" or "click: $root.incrementClickCounter".