containerless statements of knockoutjs is not work

2019-07-21 10:52发布

问题:

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