I'm trying to apply an input mask to a telephone field. It works until I apply KnockoutJS binding, which removes the mask until the field receives focus.
Does not work: 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());
Works: 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
});
})