Chr*_*ris 5 knockout.js knockout-validation
我正在尝试本地化KnockoutJS验证插件,但我需要能够在运行中切换语言.这个插件有一个问题,但它已经超过2年了(并且仍然开放).
我只是想做的是在加载所有内容后切换验证消息的语言.这是一个例子(可以在小提琴上看到: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>
Run Code Online (Sandbox Code Playgroud)
使用以下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());
Run Code Online (Sandbox Code Playgroud)
我注意到在淘汰代码中,错误的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;
}
};
Run Code Online (Sandbox Code Playgroud)
您的代码会更新本地化,但新消息仅在下一次更新时有效。
将 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();
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
854 次 |
| 最近记录: |