I am wondering whether there is a reason to prefer a prototype function / viewModel function over the other.
Say you wanted to represent an integer 1234
as a money value like 12.34€
What I did was, create a prototype function on the Number
object:
Number.localeSeparator = 1.1.toLocaleString().substr(1, 1);
Number.prototype.centToEuro = function (separator_string) {
if (!separator_string) {
separator_string = Number.localeSeparator;
}
return (this / 100).toFixed(2).replace(".", separator_string) + "€";
}
var vm = {myMoney: ko.observable(1234)};
ko.applyBindings(vm);
This made the data binding fairly easy, because all I needed to do in the view was this:
<div data-bind="text: myMoney().centToEuro()"></div>
But instead of a prototype function, I could also create a viewModel function with almost the same code, like so:
var vm = {
myMoney: ko.observable(1234),
localeSeparator: 1.1.toLocaleString().substr(1, 1),
centToEuro: function (value_int, separator_string) {
if (!separator_string) {
separator_string = vm.localeSeparator;
}
return (value_int / 100).toFixed(2).replace(".", separator_string) + "€";
}
}
ko.applyBindings(vm);
Used in the view, it would look like this:
<div data-bind="text: centToEuro(myMoney())"></div>
As you can tell, the two HTML lines are almost exactly the same length and only vary in the approach. So the question is, which approach is to prefer?