Here I have this code:
-
One option is to do something like:
<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>
Sample here: 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);
};
};
Sample here: http://jsfiddle.net/rniemeyer/9DHHh/1/
讨论(0)
-
You can use the containerless control flow syntax, which is based on comment tags:
<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>
讨论(0)
- 热议问题