简体   繁体   English

kendo UI:我可以在绑定模板中使用条件吗?

[英]kendo UI: can I use conditions in a bound template?

I have this template: 我有这个模板:

<script id="tmpl_bound_menuitem" type="text/x-kendo-template">
    <li data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name"></a>
    </li>
</script>

A View uses that to create menu items from a menuModel: 视图使用该视图从menuModel创建菜单项:

<ul class="dropdown-menu" data-bind="source: menu_test" data-template="tmpl_bound_menuitem"></ul>

This works fine. 这很好。 But if I set this data: 但是,如果我设置此数据:

menuModel.set("menu_test", [
    { name: "MenuItem1", href:"#/route1" },
    { name: "",         style: "divider" }
]);

The result has undefined values, as expected: 结果具有未定义的值,如预期的那样:

<ul class="dropdown-menu" data-bind="source: menu_test" data-template="tmpl_bound_menuitem">
    <li class="undefined" data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name" href="#/route1">MenuItem1</a>
    </li>
    <li class="divider" data-bind="attr: { class: style }">
        <a data-bind="attr: { href: href }, text: name" href="undefined"></a>
    </li>
</ul>

Now, the question is: is it possible to make this template work for different types of menu items? 现在,问题是:是否可以使此模板适用于不同类型的菜单项?

Something like the javascript code in "normal" templates: 类似于“常规”模板中的javascript代码:

# if(href) { #<a data-bind="attr: { href: href }, text: name"></a># } #

But this doesn't work here because href is undefined. 但这在这里不起作用,因为href未定义。

Yes, you can use conditions. 是的,您可以使用条件。

If you write if (href)... you need to have href defined otherwise JavaScript will not find it. 如果编写if (href)... ,则需要定义href否则JavaScript将找不到它。 So, instead, what you should write is: 因此,您应该写的是:

# if(data.href) { #<a data-bind="attr: { href: href }, text: name"></a># } #

Where data is the variable that KendoUI automatically generates containing your object model. 其中data是KendoUI自动生成的包含对象模型的变量。

Kendo UI allows to shortcut to href because in the JavaScript code they have something like: Kendo UI允许快捷方式跳转到href因为在JavaScript代码中它们具有以下内容:

with (data) {
   // Code for expanding your template
   ...
}

But this requires having href otherwise the template expansion cannot determine if href is a global variable or a member of data. 但这需要href否则模板扩展无法确定href是全局变量还是数据成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM