Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - Custom Bindings with arguments

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?

like image 744
nomen Avatar asked Nov 28 '13 07:11

nomen


2 Answers

Answers provided here are nice tricks, but knockout actually has a way of doing this.

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

and in your custom binding:

ko.bindingHandlers.numeral(fmt) = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContent) {
    var unwrapped = ko.utils.unwrapObservable(valueAccessor());
    // unwrapped.interest... = interest
    // unwrapped.fmt... = fmt ('0%' in this case)

  }
} 

Cheers :)

like image 55
Jeroen Landheer Avatar answered Oct 13 '22 12:10

Jeroen Landheer


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));
  }
} 
like image 38
Jernej Novak Avatar answered Oct 13 '22 11:10

Jernej Novak