本文介绍了KnockoutJS if 语句在 foreach 循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<tbody data-bind="foreach: entries">
    <tr>
        <td><i class="icon-file"></i> <a href="#" data-bind="text: name, click: $parent.goToPath"></a></td>
        </tr>
</tbody>

我想要这样的东西(它是伪代码):

I would like to have something like this (it's pseudocode):

<tbody data-bind="foreach: entries">
    <tr>
        <td><i class="{{ if type == 'file' }} icon-file {{/if}}{{else}} icon-folder {{/else}}"></i> <a href="#" data-bind="text: name, click: {{ if type == 'file' }} $parent.showFile {{/if}}{{else}} $parent.goToPath {{/else}}"></a></td>
    </tr>
</tbody>

有没有可能在 KnockoutJS 上写这样的东西?

Is it possible to write something like this on KnockoutJS?

推荐答案

一种选择是:

<tbody data-bind="foreach: entries">
    <tr>
        <td>
            <!-- ko if: type === 'file' -->
                <i class="icon-file"></i>
                <a href="#" data-bind="text: name, click: $parent.showFile"></a>
            <!-- /ko -->
            <!-- ko if: type !== 'file' -->
                <i class="icon-folder"></i>
                <a href="#" data-bind="text: name, click: $parent.goToPath"></a>
            <!-- /ko -->
        </td>
    </tr>
</tbody>

示例:http://jsfiddle.net/rniemeyer/9DHHh/

否则,您可以通过将一些逻辑移动到您的视图模型中来简化您的视图,例如:

Otherwise, you can simplify your view by moving some logic into your view model like:

<tbody data-bind="foreach: entries">
    <tr>
        <td>
            <i data-bind="attr: { 'class': $parent.getClass($data) }"></i>
            <a href="#" data-bind="text: name, click: $parent.getHandler($data)"></a>
        </td>
    </tr>
</tbody>

然后,在您的视图模型上添加方法以返回适当的值:

Then, add methods on your view model to return the appropriate value:

var ViewModel = function() {
    var self = this;
    this.entries = [
        { name: "one", type: 'file' },
        { name: "two", type: 'folder' },
        { name: "three", type: 'file'}
    ];

    this.getHandler = function(entry) {
        console.log(entry);
        return entry.type === 'file' ? self.showFile : self.goToPath;
    };

    this.getClass = function(entry) {
        return entry.type === 'file' ? 'icon-file' : 'icon-filder';
    };

    this.showFile = function(file) {
        alert("show file: " + file.name);
    };

    this.goToPath = function(path) {
        alert("go to path: " + path.name);
    };
};

此处示例:http://jsfiddle.net/rniemeyer/9DHHh/1/

这篇关于KnockoutJS if 语句在 foreach 循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-06 09:09