Update html code retrieved by knockout computed array before doing javascript manipulations

44 views Asked by At

I am working with jQuery and Knockout, trying to implement pagination on a web page.

The items that are displayed are stored in a computed array and then I use jQuery to correctly display 5 elements at a time. The problem I encountered is that the HTML code is not updated soon enough after the computed array is updated. The following jQuery code does not retrieve all the elements because the HTML has not yet updated with the values stored in the computed array.

filteredLabels: KnockoutComputed<LabelVM[]>;

setPagination() {
    $(table + ' tr:gt(0)').each(function () {
        trnum++;                   
        if (trnum > maxRows) {
            $(this).hide();
        }
        if (trnum <= maxRows) {
            $(this).show();
        }
    });
}

Does anyone know how to wait for the html code to be updated before doing any kind of manipulations using jQuery?

I hope that the following gives some hindsight into what my problem is:

$('mytable').onload(function() { applyPagination() });

This does not work as there is no 'onload' function stored by the table element.

1

There are 1 answers

0
Jerin Joseph On

If the question is some thing like you have a bunch of knockout operations within the html that basically loads runtime html elements based on viewmodel values. Now we need to invoke a function in the view model once all those elements are rendered completely.

In this case you cannot always relay on onload provided by JQuery as the complete DOM which we need gets rendered at later stage when the ko codes in the html gets processed.

The trick is to include a ko code itself in the html after all your operations. Since this is also a ko code we will get back the handle once the rendering of the html using the ko parsing is completed

You can include the following line below the html and then handle your cases in the function renderingComplete specified in the component.

<span data-bind="click : $component.renderingComplete()"></span>

Hope this helps