有没有办法在KnockoutJS中为ViewModel设置全局配置?
两种可能的用例可能是:
查看Knockout Validation Plugin源代码,我看到在创建validatedObservable()时,它实际上将所有子字段分组到observableArray()中,然后遍历并应用obj.extend({ validatable: true });
。创建这样的循环是最好的方法吗?是唯一的其他替代编写代码,如self.firstName = ko.observable().trimmed()
?
我看到我可以使用<input data-bind="value: name, valueUpdate: 'afterkeydown'" />
但是有没有办法可以通过编程方式或默认情况下将其应用于每个输入? 此仍然是首选解决方案:How can I get Knockout JS to data-bind on keypress instead of lost-focus?
谢谢!
答案 0 :(得分:1)
在您想要处理多个事件时,最好使用自定义绑定:
<强> JSFIDDLE 强>
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>