Does conditional logic work under the default knoc

2019-05-29 19:11发布

The conditionals below arent working with my default template with knockout.js 2.0. It just writes out the IF statements.

  <span data-bind="foreach: admin.home.paging.pages">
        {{if $data == app.viewModel.admin.home.paging.page()}}
        <span data-bind="html: $data"></span>
        {{else}}
        <a href="#" data-bind="click: app.viewModel.admin.home.paging.searchByPage($data), html: $data"></a>
        {{/if}}

    </span>

UPDATE

I did the following instead.

 <span data-bind="foreach: admin.home.paging.pages">
        <span data-bind="html: $root.admin.home.paging.page(), visible: $data == $root.admin.home.paging.page()"></span>
        <a href="#" data-bind="click: function() { $root.admin.home.searchByPage($data); }, html: $data, visible: $data != $root.admin.home.paging.page()"></a>
    </span>

标签: knockout.js
1条回答
Anthone
2楼-- · 2019-05-29 20:02

Your code is using jquery tmpl but by default Knockout uses its native template engine. If you want jquery tmpl, you must override the native engine. If you want the native engine you can use the if binding in the native templates:

<span data-bind="foreach: admin.home.paging.pages">
        <!-- ko if: $data === app.viewModel.admin.home.paging.page() -->
            <span data-bind="html: $data"></span>
        <!-- /ko -->
        <!-- ko if: $data !== app.viewModel.admin.home.paging.page() -->
            <a href="#" data-bind="click: app.viewModel.admin.home.paging.searchByPage($data), html: $data"></a>
        <!-- /ko -->
</span>

However, I recommend a few changes too. I would abstract the logic from your html and make a function in your viewmodel performs the evaluation and returns true/false. For example

<!-- ko if: isSamePage() -->

I would shorten your object hierarchy a bit too, if you can. Also, consider using the with block.

If you are iterating through admin.home.paging.pages, then each object inside of that loop is a child of that object hierarchy. In other words, you don;t have to keep specifying the entire object chain.

查看更多
登录 后发表回答