2012-02-07 186 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>