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?
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 :)
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With