Does conditional logic work under the default knockout.js 2.0 template engine?

心不动则不痛 提交于 2019-12-22 12:29:07

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/9810777/does-conditional-logic-work-under-the-default-knockout-js-2-0-template-engine

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