几乎就在那里,只需要在点击提交按钮并且该字段添加了警报类后才显示弹出窗口。
注意:悬停仅适用于绑定处理程序中isValid为true,否则测试不为true需要单击而不是悬停:S
http://jsfiddle.net/hotdiggity/UUb4M/
HTML:
<input data-bind="value: lastName, popover: isValidField" data-placement="below" data-title="Alert" data-content="We have identified this information is incorrect and must be updated."/>
JS:
self.lastName = ko.observable().extend({ required: true });
self.isValidField = ko.observable();
this.submit = function () {
if (self.errors().length === 0) {
alert('Thank you.');
} else {
self.errors.showAllMessages();
self.isValidField(self.lastName.isValid());
}
};
结合:
ko.bindingHandlers.popover = {
init: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
valueUnwrap = ko.unwrap(value),
allBindings = allBindingsAccessor(),
isValid = allBindings.value;
if (isValid) {
$(element).popover({
trigger: "hover"
});
} else {
$(element).popover("hide");
}
},
Update: //See jsfiddle link above (the same code)
答案 0 :(得分:1)
这是适合您的工作版本。仅当未满足lastName
字段的验证且仅在单击提交按钮时,才会显示弹出窗口。如果用户在lastName
字段中输入内容,它就会消失。见updated fiddle
绑定处理程序的update
函数会创建对其访问的observable的依赖关系,因此在更改observable时,将触发绑定处理程序的update
。在您的情况下,我使用isValidField
可观察对象。请参阅代码中的注释
var viewModel = function () {
var self = this;
self.lastName = ko.observable().extend({ required: true });
self.isValidField = ko.observable();
// once the popover is shown, we want it to go away if the user types something
// into the lastName field. We do this by triggering the popover binding handler
// by changing the value of isValidField
self.lastName.subscribe(function(val){
if(val && val.length > 0){ self.isValidField(true); }
});
// need to create your errors object
self.errors = ko.validation.group(self);
this.submit = function () {
if (self.errors().length === 0) {
alert('Thank you.');
} else {
self.errors.showAllMessages();
// change the value of isValidField to trigger the popover binding handler's
// update
self.isValidField(self.lastName.isValid());
}
};
};
ko.bindingHandlers.popover = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
valueUnwrap = ko.unwrap(value);
if (valueUnwrap === false) {
$(element).popover('show');
} else {
$(element).popover("destroy");
}
}
};