我正在使用该插件:https://github.com/plentz/jquery-maskmoney格式化我的资金编辑器......
我尝试在该编辑器中使用KnockoutJS,但它不起作用......没有那个掩码一切正常......
我的代码测试很简单:
<input id="Price" data-bind="value: Price" type="text" name="Price">
Javascript to Mask input
$("#Price").maskMoney({ symbol: 'R$ ', showSymbol: true, thousands: '.', decimal: ',', symbolStay: false });
和KnockoutJS
var ViewModel = function () {
this.Price = ko.observable();
this.PriceFinal= ko.computed(function () {
return this.Price()
}, this);
};
ko.applyBindings(new ViewModel());
答案 0 :(得分:14)
您还可以使用Knockout注册MaskMoney的绑定处理程序,例如:
$(document).ready(function () {
ko.bindingHandlers.currencyMask = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().currencyMaskOptions || {};
$(element).maskMoney(options);
ko.utils.registerEventHandler(element, 'focusout', function () {
var observable = valueAccessor();
var numericVal = parseFloat($(element).val().replace(/[^\.\d]/g, ''));
numericVal = isNaN(numericVal) ? 0 : numericVal;
observable(numericVal);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).unmaskMoney();
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(value);
$(element).trigger('focus');
}
};
});
然后作为你的装订:
<input type="text" data-bind="currencyMask: MyModel.TotalCost, currencyMaskOptions: { symbol: '$', showSymbol: true, thousands: ',', precision: 0 }" />
请注意,我稍微调整了MaskMoney插件以使用input.on('focusout.maskMoney', blurEvent);
而不是input.bind('blur.maskMoney',blurEvent);
,因为它没有触发通过鼠标点击失去焦点的更新,仅在标签上。
我是Knockout的新手,并且已经发现绑定处理程序方法非常适合像这样的插件和日期选择器等。
答案 1 :(得分:11)
您应该使用可写的计算可观察量。
function MyViewModel() {
this.price = ko.observable(25.99);
this.formattedPrice = ko.computed({
read: function () {
return '$' + this.price().toFixed(2);
},
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
答案 2 :(得分:0)
如果您使用的是jquery.formatcurrency,则可以执行以下操作:
ko.bindingHandlers.currencyMask = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().currencyMaskOptions || {};
$(element).formatCurrency(options);
$(element).keyup(function () {
$(element).formatCurrency(options);
});
ko.utils.registerEventHandler(element, 'focusout', function () {
var observable = valueAccessor();
observable($(element).val());
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).formatCurrency('destroy');
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(value);
$(element).trigger('focus');
}
};
<input data-bind="currencyMask: priceVal, currencyMaskOptions: { roundToDecimalPlace: 0 }" />