Stéphan
Stéphan

Reputation: 327

Knockoutjs default loader doesn't show up on first click

I'm using a knockoutjs extension to place a loader on top of an element that is loaded from an ajax request so that a loading gif is show while the request is executing.

The fiddle is very basic:

The problem is, the very first time I click on an avatar, the loading icon isn't shown but all subsequential clicks works. What am I missing here?

Thanks!

Upvotes: 0

Views: 161

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The issue that you are seeing is related to having both with and your custom binding on the same element. When the value is null, the with binding clears the child elements. This removes your loader (although it has already been copied off as part of the "template" used by the with binding), but it is put back when you populate infos. Having them on the same element also means that the bindings fires twice (once from changing infos and once from updating isAvatarLoading.

The easy way to fix this one is to split out the bindings like:

<div class="avatar" style="margin-left: 55px;" data-bind="loadingWhen: isAvatarLoading">
    <div data-bind="with: infos">
        <div data-bind="text: firstName"></div>
        <div data-bind="text: lastName"></div>
        <div data-bind="text: age"></div>
        <div data-bind="text: description"></div>
        <div style="margin-left: 55px;" id="" data-bind="with: image">
            <img data-bind="attr: { src: Url }" />
            <div data-bind="text: Description"></div>
        </div>
    </div>
</div>

If you don't want to add another element, then you could use the containerless with syntax like:

<div class="avatar" style="margin-left: 55px;" data-bind="loadingWhen: isAvatarLoading">
    <!-- ko with: infos -->
        <div data-bind="text: firstName"></div>
        <div data-bind="text: lastName"></div>
        <div data-bind="text: age"></div>
        <div data-bind="text: description"></div>
        <div style="margin-left: 55px;" id="" data-bind="with: image">
            <img data-bind="attr: { src: Url }" />
            <div data-bind="text: Description"></div>
        </div>
    <!-- /ko -->
</div>

Sample: http://fiddle.jshell.net/rniemeyer/75Lyn/

Upvotes: 1

Related Questions