我在頁面上有一個元素,如下所示:<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>滑塊使用類似的邏輯設置小時和分鐘的持續(xù)時間就可以了://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拖動人數統(tǒng)計滑塊時再也不會被調用。直接綁定到原始數據的另一個范圍Params().ChosenCount會不斷更新,因此值可以正常變化。類似地,綁定到的滑塊Params().ChosenDuration正在更新值,并且FormattedDuration()每次值更改時都會被調用,并提供一個新的格式化字符串以進入范圍
為什么以這種方式更改此格式化函數會導致 Knockout 綁定開始工作?
函數式編程
2023-09-07 16:55:25