0

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:

  • It loads a list of avatars and shows the loading image while the ajax request is executing.
  • Then, when you click an avatar, it's details are loaded into another placeholder and a loading icon is also shown while the request is executing.

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!

4

1 回答 1

1

您看到的问题与with在同一元素上同时拥有和自定义绑定有关。当值为 null 时,with绑定会清除子元素。这将删除您的加载程序(尽管它已经作为with绑定使用的“模板”的一部分被复制),但是当您填充infos. 将它们放在同一个元素上也意味着绑定会触发两次(一次来自更改infos,一次来自更新isAvatarLoading.

解决这个问题的简单方法是拆分绑定,例如:

<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>

如果您不想添加其他元素,则可以使用无容器with语法,例如:

<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>

示例: http: //fiddle.jshell.net/rniemeyer/75Lyn/

于 2013-04-25T14:19:20.870 回答