我正在使用映射插件。每当有人从文本框中取走焦点时,我就会有'模糊'事件。我想知道旧值是否与新值不同。这适用于“输入”键。出于某种原因,每当我更改值并按回车键时,我首先得到此控制台输出; 'oldValue | NEWVALUE”。然而,当'模糊'发射时,情况并非如此。我得到'newValue | NEWVALUE'
怎么样?如何在模糊处获得新旧值?
HTML:
<input class="percent-text" data-bind="text: Percent, value: Percent, event: { keypress: $root.percentUpdate, blur: $root.percentUpdate }" type="number" min="1" max="100" oninput="maxlength(this)" maxlength="3" />
淘汰赛:
self.percentUpdate = function (data, event) {
if (event.keyCode === 13 || event.type == 'blur') {
var $target = $(event.currentTarget);
console.log(data.Percent() + " | " + event.target.value);
}
return true;
};
答案 0 :(得分:1)
您可以使用您的方法(我有一个成功的测试用例),但正如@AnotherDev所说,使用内置工具更简单。在subscribe
功能中,您可以在之前访问值,在之后访问,并相应地对其进行操作。如果您以后仍希望能够检索以前的值,则可以使用缓存前面的值,甚至所有前面的值(在数组中)轻松执行此操作。请注意,小提琴中cachedPercent(s)
可观察的唯一原因是更新viewModel JSON;在一个真正的应用程序中,我将使用普通数组/数字(和私人变量中的ev。)。
在下面的小提琴中测试它;在这种方法中,ENTER
密钥功能只需要手动调用valueHasMutated
来通知订阅功能。
function App(percent) {
var self = this;
this.cachedPercent = ko.observable(percent || 0);
this.cachedPercents = ko.observableArray([percent || 0]);
this.PercentRaw = ko.observable(percent || 0);
// Percent stores an integer, and is ratelimited to make sure
// that the value isn't stored 1000x every time the user increments
this.Percent = ko.computed(function() {
return parseInt(self.PercentRaw());
}).extend({rateLimit: 500});
this.storePercents = this.Percent.subscribe(function(oldVal) {
// delete this if clause if you want to manually check somewhere else
// because this tells JS not to store any value when similar to the previous one
if (self.cachedPercent() !== oldVal) {
self.cachedPercent(self.Percent());
self.cachedPercents.splice(0, 0, self.Percent());
}
}, null, 'beforeChange');
}
ko.applyBindings(new App(50));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: PercentRaw,
event: {keydown: function(d, e) { if (e.keyCode === 13) PercentRaw.valueHasMutated(); } " type="number" min="1" max="100" maxlength="3" class="percent-text" />
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
答案 1 :(得分:0)
Knockout更新模糊值,并且值可能会在模糊事件之前更新。我不确切地知道你要做什么,但我会考虑使用.subscribe和.subscribe与beforeChange。
http://knockoutjs.com/documentation/observables.html
例如
data.Percent.subscribe(function(newValue) {
alert(newValue)
});
和
data.Percent.subscribe(function(oldValue) {
alert(oldValue)
}, null, "beforeChange");