我正在尝试将输入掩码应用于电话字段。它一直有效,直到我应用KnockoutJS绑定,它会移除掩码,直到该字段获得焦点。
不起作用: http://jsfiddle.net/8r6fe/
$('[data-mask]').each(function () {
console.log('mask');
$this = $(this);
var mask = $this.attr('data-mask') || 'error...', mask_placeholder = $this.attr('data-mask-placeholder') || 'X';
$this.mask(mask, {
placeholder: mask_placeholder
});
})
var ViewModel = function() {
this.firstName = ko.observable("");
this.lastName = ko.observable("");
this.phone = ko.observable("");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
this.firstName('John');
this.lastName('Doe');
this.phone('1231231234');
};
ko.applyBindings(new ViewModel());
使用: http://jsfiddle.net/gxhjn/
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
$('[data-mask]').each(function () {
console.log('mask');
$this = $(this);
var mask = $this.attr('data-mask') || 'error...', mask_placeholder = $this.attr('data-mask-placeholder') || 'X';
$this.mask(mask, {
placeholder: mask_placeholder
});
})
答案 0 :(得分:6)
我不认为这是一个淘汰赛问题,但设计掩码输入插件的方式存在问题:您的初始值必须与掩码标准相匹配。即使您摆脱淘汰赛并只使用jQuery的val()
函数将值设置为“1231231234”,您也会看到相同的行为。
<强>更新强>
抱歉,错过了您的“作品”链接。我首先要建议一个自定义绑定处理程序。看起来这是要走的路。它在文件被knockout更新后应用了掩码,然后使用新的掩码值更新视图模型(如果这是你想要的):
ko.bindingHandlers.maskedInput = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
ko.bindingHandlers.value.init(element, valueAccessor, allBindings, viewModel, bindingContext);
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
ko.bindingHandlers.value.update(element, valueAccessor, allBindings, viewModel, bindingContext);
$(element).mask(allBindings.get('mask'));
valueAccessor()($(element).val());
}
};
以下是您更新的小提琴:http://jsfiddle.net/8r6fe/3/