条件逻辑是否可以在默认的kickout.js 2.0模板引擎下工作? [英] Does conditional logic work under the default knockout.js 2.0 template engine?

查看:88
本文介绍了条件逻辑是否可以在默认的kickout.js 2.0模板引擎下工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的条件不能与我的默认模板一起使用knockout.js 2.0.它只是写出IF语句.

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>

更新

我改为执行以下操作.

 <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>

推荐答案

您的代码正在使用jquery tmpl,但默认情况下,Knockout使用其本机模板引擎.如果要使用jquery tmpl,则必须重写本机引擎.如果需要本机引擎,可以在本机模板中使用if绑定:

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>

但是,我也建议您进行一些更改.我会从您的html中提取逻辑,并在您的viewmodel中使一个函数执行评估并返回true/false.例如

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() -->

如果可以的话,我也会稍微缩短您的对象层次结构.另外,请考虑使用with块.

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

如果要遍历admin.home.paging.pages,则该循环内的每个对象都是该对象层次结构的子级.换句话说,您不必继续指定整个对象链.

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.

这篇关于条件逻辑是否可以在默认的kickout.js 2.0模板引擎下工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆