问题描述
我正在尝试以某种方式动态地将 i18next 翻译与 Knockout.js 一起使用,但我不知道如何.
I'm trying to somehow dynamically use i18next translations together with Knockout.js, but I cant figure out how.
自定义 Knockout 绑定或 i18next jQuery 插件似乎都无法处理可观察值.
Neither a custom Knockout binding or the i18next jQuery plugin seems to work with observable values.
可以在这里找到我想要实现的演示:http://jsfiddle.net/rdfx2/1/
A demo of what I'm trying to achieve can be found here: http://jsfiddle.net/rdfx2/1/
一种解决方法是这样的,但如果可能的话,我宁愿避免这种情况:
A workaround is something like this, but I'd rather avoid that, if possible:
<div data-bind="text: translate('key', observable)"></div>
self.translate = function (key, value) {
return i18next.t(key, {
"var": value
});
};
谢谢,
推荐答案
我对 i18next 不是很熟悉,所以我可能会错误地使用 i18next,但是您可以通过创建 bindingHandler 轻松实现这一点.支持传递可选选项的这种 bindingHandler 的一个非常简单的版本可能如下所示:
I'm not very familiar with i18next, so I might be using i18next incorrectly, but you could easily achieve this by creating a bindingHandler. A very simple version of such a bindingHandler, which supports passing optional options, could look like:
ko.bindingHandlers['translatedText'] = {
update: function(element, valueAccessor, allBindings){
var key = ko.unwrap(valueAccessor());
var options = ko.toJS(allBindings.get('translationOptions') || {});
var translation = i18n.t(key, options);
element.innerText = translation;
}
};
给定以下 i18next 初始化代码:
Given the following i18next initialization code:
i18n.init({
lng: "en",
debug: true,
resStore: {
en: {
translation: {
'myTextKey': 'My translated value is "__value__"',
'otherTextKey': 'This is just a text which does not use options'
}
}
}
});
您可以将它与以下 HTML 一起使用:
You could use it with the following HTML:
<input type="text" data-bind="value: input, valueUpdate: 'afterkeydown'"/>
<div data-bind="translatedText: 'myTextKey', translationOptions: { value: input }"></div>
<div data-bind="translatedText: 'otherTextKey'"></div>
以及以下视图模型:
function ViewModel(){
this.input = ko.observable();
}
ko.applyBindings(new ViewModel);
我已将上述代码保存到 jsfiddle 中,您可以在 http://jsfiddle.net/md2Hr/
I have saved the above code to a jsfiddle which you can find at http://jsfiddle.net/md2Hr/
这篇关于如何在 i18next 中使用 Knockout observables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!