Reputation: 341
Is there a way to set a global configuration for a ViewModel in KnockoutJS?
Two possible use-cases could be:
Looking at the Knockout Validation Plugin source, I see that when creating a validatedObservable(), it's really grouping all of the sub fields into an observableArray() which it then traverses and applies obj.extend({ validatable: true });
. Is creating such a loop the best way? Is the only other alternative writing code like self.firstName = ko.observable().trimmed()
?
I see that I can use <input data-bind="value: name, valueUpdate: 'afterkeydown'" />
but is there a way that I can apply this to each input programmatically or by default? Is this still the preferred solution: How can I get Knockout JS to data-bind on keypress instead of lost-focus?
Thanks!
Upvotes: 0
Views: 807
Reputation: 8413
In you want to handle multiple events, it would be best to use custom bindings:
ko.bindingHandlers.onChange = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
var value = valueAccessor();
var el = $(element);
el.on({
change: function () {
value(el.val());
},
keyup: function () {
value(el.val());
}
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
}
};
var model = {
name: ko.observable('John')
};
ko.applyBindings(model);
Html:
<input type="text" data-bind="onChange: name, value: name" />
<div data-bind="text: name"></div>
Upvotes: 1