我通过在表格单元格中输入值来将数据更新到数据库中,如果验证失败,我需要将焦点设置在同一个单元格上。这个表是通过knockout.js视图模型限制的。
self.FirstName = ko.observable(report.OverallRetention).extend({
reportValueChange: {
property: firstName
}
});
ko.extenders.reportValueChange = function(target, option) {
debugger;
var _oldValue;
target.setFocus = function(val) {
target.hasfocus = val;
};
target.subscribe(function(oldValue) {
_oldValue = oldValue;
}, null, 'beforeChange');
target.subscribe(function(newValue) { ///////Want to set set focus here.
答案 0 :(得分:0)
你不会只使用hasFocus数据绑定吗?
https://jsfiddle.net/0o89pmju/52/
单击清除名称按钮,验证将失败。并且将在名字上设置自动对焦。
我没有完全关注你的扩展程序,所以我使用了文档http://knockoutjs.com/documentation/extenders.html中所需的一个
HTML
<p data-bind="css: { error: firstName.hasError }">
<input data-bind='value: firstName, valueUpdate: "afterkeydown", hasFocus: firstName.hasError' />
<span data-bind='visible: firstName.hasError, text: firstName.validationMessage'> </span>
</p>
<p data-bind="css: { error: lastName.hasError }">
<input data-bind='value: lastName, valueUpdate: "afterkeydown"' />
<span data-bind='visible: lastName.hasError, text: lastName.validationMessage'> </span>
</p>
<p>
<button data-bind="click: clearName">clear first name</button>
</button>
</p>
JS
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
function AppViewModel(first, last) {
var self = this;
this.firstName = ko.observable(first).extend({
required: "Please enter a first name"
});
this.lastName = ko.observable(last).extend({
required: ""
});
this.clearName = function() {
self.firstName('');
self.lastName('');
}
}
ko.applyBindings(new AppViewModel("Bob", "Smith"));