سؤال

I'm attempting to localize the KnockoutJS validation plugin, but I need to be able to switch between languages on the fly. There's an issue open on the plugin but it's over 2 years old (and still open).

What I'm simply trying to do is switch the languages of the validation messages after everything is loaded. Here's an example (can be seen on the 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>

With the following 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());

I noticed in the knockout code, the getter method for the error always returns the first localization error string. How do I "reinitialize" the error strings?

From KnockoutJS line 736:

var errorMsgAccessor = function () {
    if (!config.messagesOnModified || isModified) {
        return isValid ? null : obsv.error; <<<< obsv.error is always the first error message
    } else {
        return null;
    }
};
هل كانت مفيدة؟

المحلول

Your code updates the localization, but the new messages will work only on the next update.

Replace switchLanguage with this:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top