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

66 Views Asked by At

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);
            }
        };
...
)};
2

There are 2 best solutions below

0
Razi Syed On BEST ANSWER

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".

0
DrPepper On

Is it possible you are in a nested situation? I sometimes run across this when I bind to a view with multiple view models. try adding the data-bind='with: nameOfTheViewModel' to the table data tag: 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>

you might need to append $Parent as well. data-bind='with: $Parent.nameOfTheViewModel'