gpt4 book ai didi

knockout.js - KnockoutJS 实时验证本地化

转载 作者:行者123 更新时间:2023-12-04 21:16:02 24 4
gpt4 key购买 nike

我正在尝试本地化 KnockoutJS 验证插件,但我需要能够即时在语言之间切换。有一个 issue open on the plugin但它已经超过 2 年了(并且仍然开放)。

我只是想做的是在加载所有内容后切换验证消息的语言。这是一个例子(可以在 fiddle 上看到: http://jsfiddle.net/Kikketer/S6j2q/ )

<input data-bind='value: phone' />
<div data-bind="text: phone"></div>
<button type='button' data-bind="click: v">Validate</button>
<button type='button' data-bind='click: switchLanguage'>Switch Language</button>

使用以下 JS:
ko.validation.configure({
registerExtenders: true
});
// If I localize right away, things work
ko.validation.localize({required: '**Required'});

var InterviewTwo = function() {
// Standard "required" validator
this.phone = ko.observable().extend({required: true});

// Group all of the validators
this.errors = ko.validation.group(this);

// Validation function
this.v = function() {
this.errors.showAllMessages();
};

// Switching languages after or before the validation
this.switchLanguage = function() {
// If I localize later, nothing is changed.
ko.validation.localize({required: 'eh... sorta?'});
ko.validation.registerExtenders();
};
};

ko.applyBindings(new InterviewTwo());

我注意到在 knockout 代码中,错误的 getter 方法总是返回第一个本地化错误字符串。如何“重新初始化”错误字符串?

从 KnockoutJS 第 736 行:
var errorMsgAccessor = function () {
if (!config.messagesOnModified || isModified) {
return isValid ? null : obsv.error; <<<< obsv.error is always the first error message
} else {
return null;
}
};

最佳答案

您的代码会更新本地化,但新消息仅适用于下一次更新。

用这个替换 switchLanguage:

this.switchLanguage = function() {
// If I localize later, nothing is changed.
ko.validation.localize({required: 'eh... sorta?'});
for (var prop in this)
if (ko.isObservable(this[prop]) && typeof(this[prop].valueHasMutated) === 'function')
this[prop].valueHasMutated();
};

Fiddle

关于knockout.js - KnockoutJS 实时验证本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23485583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com