How to hide div in Knockout.js before loading JSON?

I am using Knockout.js and trying to hide and show sections of the page while loading JSON. Loader.gif should show while there is no data, and the template should be displayed after the data exists. Here is the HTML:

<section class="container">
    <div class="loader" data-bind="visible: $data === undefined">
        <img src="/static/images/loader.gif" alt="Loading">
    </div>
    <div id="mainArea" data-bind="visible: $data !== undefined">
        [The main template is here.
            It should only show after the JSON has loaded]
    </div>
    ...

The loader.gif section shows and hides as expected, but the template does not hide at boot time. I added display: nonea CSS file so that it doesnโ€™t show until the bindings are applied and the data is loaded, but when I do this, it #mainAreanever displays at all.

I also tried to use data-bind="visible: myObservableArray().length > 0", but this also does not work.

Any ideas?

+4
source share
1 answer

, dataLoaded. false viewmodel. AJAX true. visible -binding:

<div class="loader" data-bind="visible: !dataLoaded">
    <img src="/static/images/loader.gif" alt="Loading">
</div>
<div id="mainArea" data-bind="visible: dataLoaded">
    <!--The main template is here.
        It should only show after the JSON has loaded-->
</div>

false AJAX.

:

var self = this;
/* ... */
self.dataLoaded = ko.observable(false);
/* ... */
function successCallback(result) {
    /* do whatever you need with your AJAX result */
    self.dataLoaded(true);
}
/* ... */
self.getTheData = function(optionalParams) {
    /* ... */
    self.dataLoaded(false);
    $.getJSON(someUrl, successCallback);
}

setTimeout ajax:

http://jsbin.com/zizidofidu/edit?html,js,output

, display: none;, true, CSS, .

+4

All Articles