Can I create a custom binding that uses other bindings in knockout.js

前端 未结 2 941
南笙
南笙 2021-02-07 19:22

I have a custom binding for translations:

ko.bindingHandlers.lang = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)          


        
相关标签:
2条回答
  • 2021-02-07 19:54

    Can you not just make your translation a normal function, and then call it from your table row binding?

    var translate = function(text)
    {
            this.lang = [
                'text1':'text1 translated'
                ,'text2':'text2 translated'
            ];
        },
            var translatedString = this.lang[text];
            return translatedString;
        }
    };
    

    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:

    ko.bindingHandlers.tableRow = {
        update : function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var text1 = valueAccessor()[2] ? translate(valueAccessor()[0]) : valueAccessor()[0];
            var text2 = valueAccessor()[2] ? translate(valueAccessor()[1]) : valueAccessor()[1];
            $(element).html("<td>" + text1 + "</td><td>" + text2 + "</td>");
        }
    }
    

    Then you can call it directly from bound elements:

    <span data-bind="text: translate(text1())"></span>
    
    0 讨论(0)
  • 2021-02-07 20:02

    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):

    ko.bindingHandlers.lang.init(element, valueAccessor, allBindingsAccessor, viewModel)
    

    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:

    var value = valueAccessor(); 
    var newValueAccessor = function() {
        return translatedString; }; 
    ko.bindingHandlers.lang.init(element, newValueAccessor,
           allBindingsAccessor, viewModel);
    
    0 讨论(0)
提交回复
热议问题