我已经定义了一个名为model.customDifficultySettings
的视图模型,下面显示了其中的一部分。它使用一个称为precision的扩展程序,该扩展程序只是扩展程序示例的重命名版本,用于舍入到Knockout.js文档中显示的X个小数。
ko.extenders.precision = function(target, precision) { //create a writable computed observable to intercept writes to our observable var result = ko .pureComputed({ read: target, //always return the original observables value write: function(newValue) { var current = target(), roundingMultiplier = Math.pow(10, precision), newValueAsNum = isNaN(newValue) ? 0 : +newValue, valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier; //only write if it changed if (valueToWrite !== current) { target(valueToWrite); } else { //if the rounded value is the same, but a different value was written, force a notification for the current field if (newValue !== current) { target.notifySubscribers(valueToWrite); } } } }) .extend({ notify: "always" }); //initialize with current value to make sure it is rounded appropriately result(target()); //return the new computed observable return result; }; model.customDifficultySettings = { econBase: ko .observable(0) .extend({ rateLimit: { timeout: 750 }, precision: 3 }), };
在以后的
makeGame()
函数中,我们确保model.customDifficultySettings.econBase()
可观察到的值与所选难度值的值匹配
model.customDifficultySettings.econBase( difficultyInfo[model.newGameDifficultyIndex() || 0].econBase ); console.log(model.customDifficultySettings.econBase()); console.log(difficultyInfo[model.newGameDifficultyIndex() || 0].econBase);
第一次运行时
difficultyInfo[model.newGameDifficultyIndex()].econBase
的值为0.55。我希望控制台将两者都显示为0.55,或者如果出了点问题,都将显示为0。但是,对于可观察对象,返回的值是0,但是对于输入的值,返回的是0.55。
如果我在代码运行后从控制台查询可观察对象,它将返回期望值0.55。
如果更改了难度级别,导致makeGame()
再次运行,则所有值均已正确设置。仅在第一次运行时才会出现此问题。
我已将问题追溯到精度扩展器。卸下扩展器,一切正常。但是,在我刚刚复制示例代码时,我尚不清楚它的作用以及为什么会发生此问题。
作为一种解决方法,我可以将所有可观察到的默认值设置为与困难级别的默认值匹配,但我希望避免这种情况。
我已经定义了一个名为model.customDifficultySettings的视图模型,其一部分如下所示。它使用一个称为precision的扩展程序,它只是扩展程序示例的重命名版本,用于...
由于我先声明了rateLimit
,因此似乎出现了问题。如果我将其反转并首先声明precision
,那么一切都会按预期进行。所以我的视图模型现在看起来像这样: