I have a custom binding for translations:
ko.bindingHandlers.lang = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
this.lang = [
'text1':'text1 translated'
,'text2':'text2 translated'
];
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var keyword = valueAccessor();
var translatedString = this.lang[keyword];
$(element).text(translatedString );
}
};
Which I use like this:
<span data-bind="lang:'text1'"></span>
However, I also have a binding for creating a table row formating:
ko.bindingHandlers.tableRow = {
update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).html("<td>" + valueAccessor()[0] + "</td><td>" + valueAccessor()[1] + "</td>");
}
}
Which I use like this:
<tr data-bind="tableRow:['text1','text2']"></tr>
To the question:
Now I would like to combine these bindings so I could call my tableRow binding like this:
<tr data-bind="tableRow:[lang:'text1','text2']"></tr>
The code above is ofcourse only for example, in reality there's more going on in these bindings.
I have read through the documentation multiple times and spent a long time searching for a solution but couldn't find anything. Maybe because this can't be done?
All you need to do is relay or modify the values from one bindingHandler to the other ones you want to activate.
So, in your tablerow handler, call init and update (in their respective functions):
Modify the parameters as needed of course. It's likely you'll grab one of the values from your array and pass it as the second parameter to init and update.
This is a great way to activate other standard built in bindings as well.
Update: Adding the comment from @Joche just to make this more readable:
Can you not just make your translation a normal function, and then call it from your table row binding?
You could then pass in an extra parameter to the tableRow method to indicate whether you want translation or not:
You could then call this in your table row binding function:
Then you can call it directly from bound elements: