我有一个使用 Knockout.js 的简单训练案例,我想根据范围 slider 值显示不同数量的苹果。这是 slider :
<input data-bind="value: currentAppleCount" type="range" step="1" min="2" max="10"/>
每次用户移动 slider handle 时,都应使用 renderApples(appleCount)
等方法用适当数量的苹果重新绘制 UI 的一部分。
我应该使用 model.currentAppleCount.subscribe(renderApples) 还是有更好的方法,因为这种情况很简单,并且 knockoutjs 文档指出“您通常不需要手动设置订阅”。另外,作为一种良好的做法,renderApples
方法应该接收 appleCount
作为参数,还是直接访问 model.currentAppleCount
observable。
编辑:
问题是我需要使用带有添加和删除方法的第三方 API。
最佳答案
使用ko.compulated
返回适当长度的数组。每次更新引用的可观察量时,都会重新评估计算属性。
function ViewModel() {
this.currentAppleCount = ko.observable(2);
this.apples = ko.computed(function () {
var currentAppleCount = this.currentAppleCount();
var apples = [];
for (var i = 1; i <= currentAppleCount; i++) {
apples.push(i);
}
return apples;
}, this);
}
ko.applyBindings(new ViewModel());
或者,您可以返回完整数组的一部分。这样您就可以保留对象实例。
<input data-bind="value: currentAppleCount" type="range" step="1" min="2" max="10"/>
<ul data-bind="foreach: apples">
<li>Apple #<span data-bind="text: $data"></span></li>
</ul>
关于javascript - observable.subscribe 或自定义绑定(bind)或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13790242/