问题
I am not sure if this is possible, but I have a scenario where I have a validation system which notifies my validation system when something has become valid/invalid via a dependant observable. Now this works great when a user is filling out a form as the dependantObservable is driven off the underlying observables value changing. (i.e if the Name property changes, it will re-evaluate the isValid
dependant observable, which will in turn notify my binding which hooks into the validation system).
Now my problem is that if the user doesn't touch the form at all and just goes straight to submission, it will not trigger the binding, as the underlying values have not changed for any observables, so no subscribers will know about any validation changes happening. Ideally I do not want to go through each observable and re-assign it its current variable to push a validation evaluation through, which would in turn trigger a change in the validation state. So as really all I want to do is get this isValid
dependantObservable to refresh for lack of a better word.
It seems quite nasty either way, but my options seem to be either:
1) Force a value change on all observables being validated against (horrible)
2) Force a re-evaluation of the isValid dependantObservable to trigger the subscriber (less horrible, but still bad)
3) Re-write the validation library to expose a forceValidation()
function which would somehow trigger everything to be re-evaluated, bypassing the need for the underlying observables to trigger the validation pipeline.
Any ideas?
回答1:
On your computed observable (isValid
) you can call notifySubscribers(currentValue)
, which will notify any subscribers with the current value. It will not re-evaluate the computed and will simply notify subscribers with the current value.
回答2:
Add binding enable: formValid
where formValid = ko.computed(return true if all values are valid)
to submit button. This way user can not submit until form is filled properly.
Use ko.validation.validateObservable(yourDependentObservable)
to revalidate field manually
or use yourObsevable.notifySubscribers()
if yourDependentObservable
depends on yourObservable
.
来源:https://stackoverflow.com/questions/9519333/manually-get-knockout-to-re-evaluate-a-dependantobservable