KnockoutJS - Custom Bindings with arguments

javascript, knockout.js

Solution

Try like this.

<td data-bind="numeral: interest, fmt : '0%'">

And the binding

ko.bindingHandlers.numeral = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContent) {
    var unwrapped = ko.unwrap(valueAccessor()), allBindings = allBindingsAccessor();
    var fmtVal = allBindings.get('fmt') || '0%'; 
    $(element).html(numeral(unwrapped).format(fmtVal));
  }
} 

Problem

I'm trying to write custom knockout bindings to some JavaScript "rendering" functions, so that I could do stuff like: ``` <td data-bind="numeral('0%'): interest"> ``` Behind the scenes, this hypothetical numeral would be doing something like: ``` ko.bindingHandlers.numeral(fmt) = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContent) { var unwrapped = ko.unwrap(valueAccessor()), allBindings = allBindingsAccessor(); $(element).html(numeral(unwrapped).format(fmt)); } } ``` I gave this definition a go, and JavaScript really didn't like me trying to abstract on the numeral key. How should I approach the problem?

Original source