1

I am trying to create a custom binding handler in knockout to total columns of data. I have an application where I need to total many columns of data and thought a custom binding handler would do the trick.

Example binding:

<span data-bind="totalAmount: Adjustments, columnName:'Amount'"></span>

The custom binding handler looks something like:

ko.bindingHandlers.totalAmount = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    var val = valueAccessor();
    var unwrappedVal = ko.unwrap(val);

    var columnName = allBindings().columnName;
    var total = 0;

    ko.utils.arrayForEach(unwrappedVal, function (item) {
        var amt = item.<columnName>();
        total += amt;
    });

    $(element).html("$" + total);
}

}

In the code above, how do I get the value of the observable associated with the propery passed in via the columnName property?

Greg P
  • 107
  • 1
  • 9
  • What about `var amt = item[columnName]();` (or even better: `var amt = ko.unwrap(item[columnName]);` ? In javascript you can reference properties by their name using the array indexer syntax. – nemesv Dec 23 '14 at 15:19
  • Worked like a champ! Thanks. – Greg P Dec 23 '14 at 15:44

0 Answers0