我在这里有这个代码:
<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>
Run Code Online (Sandbox Code Playgroud)
我想有这样的东西(它是伪代码):
<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>
Run Code Online (Sandbox Code Playgroud)
是否有可能在KnockoutJS上写这样的东西?
RP *_*yer 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>
Run Code Online (Sandbox Code Playgroud)
此处示例: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>
Run Code Online (Sandbox Code Playgroud)
然后,在视图模型上添加方法以返回适当的值:
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);
};
};
Run Code Online (Sandbox Code Playgroud)
此处示例:http://jsfiddle.net/rniemeyer/9DHHh/1/
您可以使用基于注释标签的无容器控制流语法:
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38597 次 |
| 最近记录: |