chap03 -> Custom bindings -> The currency binding

chap3
Jason Zhu 2022-04-30 20:25:28 +10:00
parent 7c1c4ee8f1
commit 98de2a5947
2 changed files with 25 additions and 10 deletions

View File

@ -1,10 +1,25 @@
ko.bindingHandlers.toggle = {
init: function (element, valueAccessor) {
var value = valueAccessor();
ko.applyBindingsToNode(element, {
click: function() {
value(!value());
}
});
}
};
init: function (element, valueAccessor) {
var value = valueAccessor();
ko.applyBindingsToNode(element, {
click: function () {
value(!value());
},
});
},
};
ko.bindingHandlers.currency = {
symbol: ko.observable("$"),
update: function (element, valueAccessor, allBindingsAccessor) {
return ko.bindingHandlers.text.update(element, function () {
var value = +(ko.unwrap(valueAccessor()) || 0);
var symbol = ko.unwrap(
allBindingsAccessor().symbol !== undefined
? allBindingsAccessor().symbol
: ko.bindingHandlers.currency.symbol
);
return symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
});
},
};

View File

@ -20,7 +20,7 @@
<tbody data-bind="foreach:catalog">
<tr data-bind="style:lineColor">
<td data-bind="text:name"></td>
<td data-bind="text:price"></td>
<td data-bind="currency:price, symbol:'€'"></td>
<td data-bind="text:stock"></td>
<td>
<button