拥有此元素(请注意计算字段)fullNumber
var NumberField = function () {
var self = this;
self.maskFormat = "0";
self.firstNumber = ko.observable("");
self.secondNumber = ko.observable("");
self.thirdNumber = ko.observable("");
self.fourthNumber = ko.observable("");
self.fifthNumber = ko.observable("");
self.fullNumber = ko.pureComputed(function() {
return [
self.firstNumber,
self.secondNumber,
self.thirdNumber,
self.fourthNumber,
self.fifthNumber ].map(ko.unwrap);
}
}
然后我就像使用它一样:
<div class="numberFields" data-bind="with: numbers">
<input id="0" class="number-ball" maxlength="2" type="tel" data-bind="twoDigits: firstNumber, maxNumber: 68">
<input id="1" class="number-ball" maxlength="2" type="tel" data-bind="twoDigits: secondNumber, maxNumber: 68">
<input id="2" class="number-ball" maxlength="2" type="tel" data-bind="twoDigits: thirdNumber, maxNumber: 68">
<input id="3" class="number-ball" maxlength="2" type="tel" data-bind="twoDigits: fourthNumber, maxNumber: 68">
<input id="4" class="number-ball" maxlength="2" type="tel" data-bind="twoDigits: fifthNumber, maxNumber: 68">
</div>
如何确保fullNumber
中没有重复的值?
答案 0 :(得分:1)
在您的计算中,您可以链接map
对您的数字的各种函数。基本上,你做了三件事:
observable
,Number
移至ko.unwrap
null
或undefined
值在普通的javascript中,但有一些“现代”功能(Array.from
,Set
):
var uniques = function(arr) {
// There are many implementations of a unique method.
// google/search for `unique js values` to learn more
return Array.from(new Set(arr));
};
var arrUnwrap = function(arr) {
return arr.map(ko.unwrap);
};
var truethyValues = function(arr) {
return arr.filter(function(val) {
return val;
});
};
var NumberField = function () {
var self = this;
self.maskFormat = "0";
self.firstNumber = ko.observable("");
self.secondNumber = ko.observable("");
self.thirdNumber = ko.observable("");
self.fourthNumber = ko.observable("");
self.fifthNumber = ko.observable("");
var numbers = [
self.firstNumber,
self.secondNumber,
self.thirdNumber,
self.fourthNumber,
self.fifthNumber ];
// Read from right to left:
// fullNumber is: unwrapped, unique, truethy numbers
self.fullNumber = ko.pureComputed(function() {
return truethyValues(uniques(arrUnwrap(numbers)));
});
}
ko.applyBindings(new NumberField());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
<input data-bind="textInput: firstNumber">
<input data-bind="textInput: secondNumber">
<input data-bind="textInput: thirdNumber">
<input data-bind="textInput: fourthNumber">
<input data-bind="textInput: fifthNumber">
</div>
<h1 data-bind="text: fullNumber"></h1>