在我最近建立的Knockout界面中,我試圖設置自動保存。它的設計使得在停止更改後1秒內可以保存。KnockoutJS貨幣綁定與實時更新
這是問題所在。默認情況下,KO依靠輸入上的模糊事件來更新viewModel。如果您在離開頁面或刷新瀏覽器之前單擊開箱,我的界面不會保存數據。
爲了解決這個問題,我啓用了valueUpdate: 'afterkeydown'
,它適用於所有字符串輸入。但是,我有一個數字PricePerLF字段被擴展,以便它始終包含一個數字值。我用建議的擴展器找到here。
ko.extenders.numeric = function(target, precision) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+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);
}
}
}
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
我該如何讓這個數字擴展器與valueUpdate: 'afterkeydown'
一起玩呢?強制它顯示一定數量的小數點也不錯,如2.80
而不是2.8
。
我很困惑。 valueUpdate:'afterkeydown'應該可以正常工作,即使使用數字擴展器。不是? –
它很難輸入小數...... –
我剛剛在這裏試過了:http://jsfiddle.net/TtPAx/我的問題是,你想如何表現?從你的問題來看,你不清楚你想如何表現。 –