【发布时间】:2014-08-09 05:17:55
【问题描述】:
我有一个模板,它绑定到一个淘汰赛 observableArray。我试图让一些东西只显示在数组中的第一个项目上。当第一个项目被删除时,成为第一个项目的下一个项目应显示此部分。它应该类似于以下代码。关键是 isFirst 函数。
HTML
<div data-bind="template: { name: 'my-template', foreach: people }"></div>
<script type="text/html" id="my-template">
<div>
<span data-bind="visible: isFirst">The first person is </span>
<span data-bind="text: name"></span>
</div>
</script>
<button data-bind="click: removeFirst">Remove First</button>
视图模型
function Person(p,name,age) {
this.parent = p;
this.name = name;
this.age = age;
this.isFirst = ko.computed(function(){
return this.parent.people.indexOf(this) === 0;
});
}
var viewModel = function() {
var self = this;
self.people = ko.observableArray();
self.people.push(new Person(self, 'Fred', 25));
self.people.push(new Person(self, 'Joe', 15));
self.people.push(new Person(self, 'Sally', 21));
self.people.push(new Person(self, 'Ann', 37));
self.people.push(new Person(self, 'Jack', 52));
self.removeFirst = function () {
people.splice(0, 1);
}
};
};
【问题讨论】:
标签: knockout.js