Last active
February 14, 2018 10:46
-
-
Save jakiestfu/7894971 to your computer and use it in GitHub Desktop.
Used to display formatted money via Knockout binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var toMoney = function(num){ | |
return '$' + (num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') ); | |
}; | |
var handler = function(element, valueAccessor, allBindings){ | |
var $el = $(element); | |
var method; | |
// Gives us the real value if it is a computed observable or not | |
var valueUnwrapped = ko.unwrap( valueAccessor() ); | |
if($el.is(':input')){ | |
method = 'val'; | |
} else { | |
method = 'text'; | |
} | |
return $el[method]( toMoney( valueUnwrapped ) ); | |
}; | |
ko.bindingHandlers.money = { | |
update: handler | |
}; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<span data-bind="money: 1234567.2"></span> <!-- Outputs $1,234,567.20 --> | |
<input type="text" data-bind="money: 1234567"> <!-- Sets value to $1,234,567.00 --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another option for the
toMoney
function, just as an illustration for the curious (in coffeescript):Cheers