问题描述
我试图以某种方式动态地使用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.
我可以在这里找到我想要实现的演示:
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,您可以在
I have saved the above code to a jsfiddle which you can find at http://jsfiddle.net/md2Hr/
这篇关于如何在i18next中使用Knockout observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!