敲除绑定错误

Knockout binding error

所以我有这个加载 Instagram 数据的图库,有时 Instagram 照片没有标题,这就是它坏掉的时候,所以最合乎逻辑的做法是检查标题是否存在,但它还是坏了。

Live example

<!-- ko if: $root.entries().length != 0 -->
        <!-- ko foreach: $root.entries() -->
            <!-- ko with: $root.entries()[$index()] -->
                <span data-bind="logger: typeof caption"></span>
                <figure>
                    <img src="" data-bind="attr: {src: images.low_resolution.url}"/>
                    <figcaption>
                            <a target="_blank" data-bind="text: user.username, attr: {href: 'http://instagram.com/' + user.username }"></a>
                         <!--ko if: typeof caption != 'null'-->
                            <span>
                                <!-- ko text: caption.text --><!-- /ko -->
                            </span>

                         <!--/ko-->
                    </figcaption>
                </figure>
            <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->

typeof 运算符没有 return null,所以你的条件实际上是无条件的:它总是尝试呈现 caption.text 即使 caption 为空。

你可以试试:

<!--ko if: caption-->

如果 caption 是 "truthy"(不是 falsenullundefined、0、空字符串等)