我在页面上有一个元素,如下所示:
<span data-bind="text: FormattedCountOfPeople"></span>
计算它的函数我首先是这样写的:
self.FormattedCountOfPeople = ko.computed(function () {
if(!self.PeopleCountFormatString) //a string like "{0} people in the conference", but set by a service call so starts out undefined
return "not set yet";
let sizes = self.Params().PermittedCounts(); //an array of discrete permitted sizes e.g. [2, 10, 30]
let size = self.Params().ChosenCount(); //value set by a jquery slider, could be any double, even 5.7435 - to achieve smooth dragging of the slider it has a small step but snaps to a permitted count
let n = nearest(size, sizes); //a "round to nearest" helper function that given args of e.g. (5.7345, [2, 10, 30]) will pick 2 because 5.7345 is nearer to 2 than 10
let s = self.PeopleCountFormatString.csFormat(n); //csformat is a helper function that performs C# style string Formatting e.g. "{0} people".csFormat(2) -> "2 people"
return s;
});
我绕了好几个小时,想知道为什么无论滑块设置是什么,页面上的文本都卡在“尚未设置”处,但是作为测试添加的另一个元素正在完美更新,而其他地方有一个不同的<span data-bind="text: Params().ChosenCount"></span>滑块使用类似的逻辑设置小时和分钟的持续时间就可以了:
//if the user picks 61.2345, it rounds to 60, then returns "1 hour". Picking 74.11 rounds to 75 then returns "1 hour, 15 min"
self.FormattedDurationText = ko.computed(function () {
var duration = self.Params().ChosenDuration();
duration = Math.round(duration / 15) * 15;
});
在不同的地方添加一些控制台日志记录,很明显,在第一次调用FormattedCountOfPeople返回“尚未设置”后,FormattedCountOfPeople拖动人数统计滑块时再也不会被调用。直接绑定到原始数据的另一个范围Params().ChosenCount会不断更新,因此值可以正常变化。类似地,绑定到的滑块Params().ChosenDuration正在更新值,并且FormattedDuration()每次值更改时都会被调用,并提供一个新的格式化字符串以进入范围
慕标琳琳
相关分类