Knockout observables with i18next
HTML
<script src="http://mbest.github.io/knockout.punches/knockout.punches.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://cdn.jsdelivr.net/i18next/1.7.1/i18next.min.js"></script>
<div id="i18next">
<fieldset>
<legend>Input</legend>
<input type="text" data-bind="value: input, valueUpdate: 'afterkeydown'" placeholder="Type something" />
</fieldset>
<fieldset>
<legend data-i18n="output">Output</legend>
<label>Observable directly in attribute, Ok:</label>
<input type="text" disabled="disabled" value="{{input}}" />
<label>Value loaded with i18next jQuery plugin, Ok:</label>
<input type="text" disabled="disabled" data-i18n="[placeholder]placeholder" />
<label class="error">i18next options with observable, Not ok:</label>
<input type="text" disabled="disabled" data-i18n="[value]value" data-i18n-options='{"value": "{{input}}"}' />
<label>i18next options with hard coded value, Ok:</label>
<input type="text" disabled="disabled" data-i18n="[value]value" data-i18n-options='{"value": "text"}' />
<label>Knockout binding with hard coded value, Ok:</label>
<input type="text" disabled="disabled" data-i18n="[value]value" data-bind="i18n-options: {'value': 'text'}" />
<label class="error">Knockout binding with observable, Not ok:</label>
<input type="text" disabled="disabled" data-i18n="[value]value" data-bind="i18n-options: {'value': input}" />
</fieldset>
</div>
CSS
fieldset {
margin-bottom: 10px
}
label {
display:block;
color: green;
}
input {
width: 50%;
padding: 5px
}
.error {
color: red
}
JavaScript
// Initialize i18next
i18n.init({
lng: "en",
debug: true,
useDataAttrOptions: true,
resStore: {
en: {
translation: {
'placeholder': 'Placeholder from i18next',
'value': 'This is your value: __value__'
}
}
}
}, function () {
// Enable dynamic attributes
ko.punches.attributeInterpolationMarkup.enable();
// Custom binding for adding i18next options
// data-bind="i18n-options: {'var': 'xxx', 'var2': 1}"
ko.bindingHandlers['i18n-options'] = {
'update': function (element, valueAccessor, allBindings) {
var value = ko.utils.unwrapObservable(valueAccessor()) || {};
var data = {};
ko.utils.objectForEach(value, function (attrName, attrValue) {
//console.log(ko.utils.unwrapObservable(attrValue));
data[attrName] = ko.utils.unwrapObservable(attrValue);
});
element.setAttribute("data-i18n-options", JSON.stringify(data));
}
};
// Activate Knockout
var ViewModel = function () {
this.input = ko.observable();
};
ko.applyBindings(new ViewModel());
// Internationalize
$("#i18next").i18n();
});