如果在foreach循环中声明了KnockoutJS

时间:2012-02-07 14:16:22

标签: knockout.js

我在这里有这段代码:

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

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

<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上写这样的东西?

2 个答案:

答案 0 :(得分:38)

一种选择是做一些事情:

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

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

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

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

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/

答案 1 :(得分:5)

您可以使用基于注释标记的无容器控制流语法:

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