本文介绍了是否可以将 KnockoutJS 与屏蔽输入一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用该插件:https://github.com/plentz/jquery-maskmoney 格式化我的货币编辑器...
I´m using that plugin : https://github.com/plentz/jquery-maskmoney to format my money editor...
我试图在那个编辑器中使用 KnockoutJS,但它不起作用......没有那个面具一切正常......
I tried to use KnockoutJS in that editor, but it does not work... Without that mask all works fine...
我的代码测试很简单:
<input id="Price" data-bind="value: Price" type="text" name="Price">
Javascript 屏蔽输入
Javascript to Mask input
$("#Price").maskMoney({ symbol: 'R$ ', showSymbol: true, thousands: '.', decimal: ',', symbolStay: false });
和 KnockoutJS
And KnockoutJS
var ViewModel = function () {
this.Price = ko.observable();
this.PriceFinal= ko.computed(function () {
return this.Price()
}, this);
};
ko.applyBindings(new ViewModel());
推荐答案
你应该使用可写的计算 observable.
You should use a writable computed observable.
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());
这篇关于是否可以将 KnockoutJS 与屏蔽输入一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!