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

前端 未结 2 1601
清歌不尽
清歌不尽 2021-02-07 19:27

I have a custom binding for translations:

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


        
2条回答
  •  别跟我提以往
    2021-02-07 19:45

    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("" + text1 + "" + text2 + "");
        }
    }
    

    Then you can call it directly from bound elements:

    
    

提交回复
热议问题