Lars Holdgaard
Lars Holdgaard

Reputation: 9966

How to avoid knockout bindings being called at page load?

I have a knockout viewmodel, which has a computed function called updatePrices. This method should never be called, unless a user toggle a checkbox inside my table.

The table is being generated by a foreach data-bind.

What I currently experience is the updatePrices method is being called for every row made in the table on page load, and then when the user toggle the checkbox. The behavior I expect, is it only calls the updatePrices when I toggle the checkbox, not on page-load.

So I basically want to avoid the methods being called on page-load. How do I do that?

My html markup:

<tbody data-bind="foreach: invoices">
    <tr>
        <td>
            <input type="checkbox" data-bind="checked: print, click:updatePrices()" />
        </td>
        <td data-bind="text: invoiceDate"></td>
        <td data-bind="text: customerName"></td>
        <td data-bind="text: amount"></td>
        <td>
            <a data-bind="attr: { href: pdfLink }">Download</a>
        </td>
        <td data-bind="text: status"></td>
    </tr>
</tbody>

My knockout function:

self.updatePrices = ko.computed(function () {
    $.ajax({
        url: '/SingleLetter/GetPriceFromUrl',
        type: 'POST',
        data: {
            pdfUrl: self.pdfLink,
        },
        dataType: 'json',
        success: function (data) {
            self.jsonPrice(data.price);

        },
        error: function (file, responseText) {
            console.log('Price error');

        }
    });

});

Upvotes: 1

Views: 1021

Answers (1)

mathewbergt
mathewbergt

Reputation: 301

First, you don't need to make updatePrices computable since it does not return any values, and does not rely on any other view model variables.

Second, your data binding for click is incorrect because you are immediately calling the function. Your data binding should look like this:

 <input type="checkbox" data-bind="checked: print, click:updatePrices" />

Upvotes: 4

Related Questions