Friday, July 11, 2014

Knockout Custom Array Data-bind

I am working on a scenario where I need to bind a div tag to multiple ko variables. I want to show these multiple ko variables as a comma separated string. One way to do this is to concatenate these variables while binding to the div element as shown below:

    <div data-bind="text: model.CostPrice() + ',' + model.SalePrice()"></div>

The above works great. But in my scenario I have to do this in multiple places. Instead of concatenating the strings within the binding, I wanted to implement a custom binding which takes multiple ko variables and concatenates these variables into strings. Here is my custom binding

    ko.bindingHandlers.displaytext = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {
            var field = valueAccessor();

            var computedtext = ko.computed(function () {
                var disptext = "";
                for (var index = 0; index < field.length; index++) {
                    if (field[index]() !== undefined && field[index]() !== "") {
                        disptext += field[index]() + ", ";
                    }
                }
                return disptext;
            });

            ko.applyBindingsToNode(element, {
                text: computedtext
            });
        }
    };

As you see in the above custom binding, I defined a computed variable which concatenates all the passed in variables. Whenever there is a change in any of the input variables, the computed variable re-computes the concatenated string and bind it. Here is how I am using it

   <div data-bind="displaytext: [model.CostPrice, model.SalePrice]"></div>

With this custom binding attribute, I can pass any number of knockout variables (which are passed as an array) and show them as a concatenated string.

No comments:

Post a Comment