2012-02-07 183 views
25

在这里,我有这样的代码:KnockoutJS如果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> 

我想有这样的事情(它的伪代码):

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

回答

36

一种选择是像做:

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

+0

http://pastie.org/3334757它是基于你的榜样我的代码, 。但它不适用于我 - 它会生成没有内容的TD。 我使用基诺-2.0.0.js – VitalyP 2012-02-07 14:56:29

+0

你可以分岔这一个吗? http://jsfiddle.net/rniemeyer/9DHHh/。我没有看到你的贴子链接有任何问题。 – 2012-02-07 16:08:14

+1

如果没有<! - ko,它运作良好:if!=='file' - > conditions - 它呈现一张没有问题的表格,但条件不起作用。 – VitalyP 2012-02-07 16:30:08

4

可以使用无容器控制流语法,它是基于注释标签:

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