containerless statements of knockoutjs is not working in hottowel SPA?

无人久伴 提交于 2019-12-10 23:48:50

问题


I was trying to use the containerless statements like <!--ko if:IsShowData==true --> of knockoutjs in hot towel template but it was not woring instead if i use visible binding with some element like div then it work very fine.(<div data-bind="visible: IsShowData==true"></div>)

Can anybody tell me if containerless statements of knockoutjs doesnt work in hot towel template?

In Default Hot towel template i added few lines in home.html and home.js as follow:

views/home.html

<section>
    <h2 class="page-title" data-bind="text: title"></h2>
</section>

<!-- ko if: active()==true -->
hiiiiiiiiiiiiiii
<!--/ko-->


<div data-bind="visible: active() == true">
    byeeeeeeeeeeeee
</div>

And In viewmodels/home.js file

define(['services/logger'], function (logger) {
    var vm = {
        activate: activate,
        active:ko.observable(false),
        title: 'Home View'
    };

    return vm;

    //#region Internal Methods
    function activate() {
        logger.log('Home View Activated', null, 'home', true);
        return true;
    }
    //#endregion
});

i will see hiiiiiiii but i will not see byeeeeee


回答1:


Your problem is not related to Knockout or to the if contenerless binding but Durandal.js (which is used by the HotTowel templates) and how Durandal handles the view model.

Because in Durandal.js your viewmodel should only contain one root element and it removes the root level comments.

From the documentation:

The view has exactly one root element. Durandal requires this. If comments are found at the root, they will be removed. In the case where more than one root element is found, they will be wrapped in a div.

So the solution is simple: just more the two text inside the section or wrap everything into a div or section:

<section>
    <h2 class="page-title" data-bind="text: title"></h2>

    <!-- ko if: active()==true -->
         hiiiiiiiiiiiiiii
    <!--/ko-->


    <div data-bind="visible: active() == true">
         byeeeeeeeeeeeee
   </div>
</section>

Or

<div>
     <section>
        <h2 class="page-title" data-bind="text: title"></h2>
     </section>

    <!-- ko if: active()==true -->
       hiiiiiiiiiiiiiii
    <!--/ko-->


     <div data-bind="visible: active() == true">
        byeeeeeeeeeeeee
    </div>
</div>

By the way instead of if: active()==true and visible: active() == true you can simple write: if: active and visible: active



来源:https://stackoverflow.com/questions/17271248/containerless-statements-of-knockoutjs-is-not-working-in-hottowel-spa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!