bbgv1w
Last Updated: February 25, 2016
·
1.222K
· emi420
Image

Optimizing Knockout.js

Today I have been working on a project that requires updates on hundreds of DOM elements when a view of my HTML5 mobile app is loaded.

In any other project, with only 10 or 20 elements to update, I write something like this:

element = document.getElementById("myDOMelement");

app.models.applyBindings(
    { 
        myData: myData
    },
    element
); 

But using this code, when there are hundreds of bindings, is very painful for the performance of the application.

A good alternative is query a limited collection of elements to update, and only when necessary (ex: when the hidden elements shows up), do the rest of the update.

First, you bind a filtered elements collection:

elements = document.querySelectorAll("#myDOMelement > .myField > [data-bind]");

for (i = 0; i < elements.length; i++) {
    app.models.applyBindings(
        { 
            myData: myData
        },
        elements[i]
    ); 
}

And then, for example when the user clicks a button that show the rest of the fields, you can bind the rest:

elements = document.querySelectorAll("#myDOMelement > .myHiddenField > [data-bind]");

for (i = 0; i < elements.length; i++) {
    app.models.applyBindings(
        { 
            myData: myData
        },
        elements[i]
    ); 
}

Using this approach, you can bind only the exact elements you need to bind, achieving a good performance optimization.

Say Thanks
Respond