Created
August 9, 2012 03:12
-
-
Save cleytonferrari/3300583 to your computer and use it in GitHub Desktop.
Formatar moeda com Knockout JS
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
//baseado em http://jsfiddle.net/digitalbush/R6MPU/ | |
jQuery(function ($) { | |
function empenhoViewModel() { | |
var self = this; | |
self.valorTotal = ko.observable().dinheiro(); | |
}; | |
var format = function (value) { | |
if (value === '' || isNaN(value)) value = 0; | |
toks = Number(value).toFixed(2).replace('-', '').split('.'); | |
var display = 'R$ ' + $.map(toks[0].split('').reverse(), function (elm, i) { | |
return [(i % 3 === 0 && i > 0 ? '.' : ''), elm]; | |
}).reverse().join('') + ',' + toks[1]; | |
return value < 0 ? '-' + display : display; | |
}; | |
ko.subscribable.fn.dinheiro = function () { | |
var target = this; | |
var writeTarget = function (valor) { | |
valor = String(valor).replace('.', '').replace(',', '.').replace(/[^0-9.-]/g, ''); | |
target(parseFloat(valor)); | |
}; | |
var result = ko.computed({ | |
read: function () { | |
return target(); | |
}, | |
write: writeTarget | |
}); | |
result.formatted = ko.computed({ | |
read: function () { | |
return format(target()); | |
}, | |
write: writeTarget | |
}); | |
result.isNegative = ko.computed(function () { | |
return target() < 0; | |
}); | |
return result; | |
}; | |
var viewModel = new empenhoViewModel(); | |
ko.applyBindings(viewModel); | |
viewModel.init(); | |
}); |
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
<!-- imput em razor (ASP.NET MVC) --> | |
@Html.TextBoxFor(x => x.ValorTotal, new { @data_bind = "value: valorTotal.formatted" }) | |
<!-- imput simples em html --> | |
<input data-bind="value: valorTotal.formatted" type="text" value=""> | |
<span data-bind="text: valorTotal.formatted"></span> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment