问题
Got simple viewModel:
function viewModel() {
enabled: ko.observable(false);
...
}
and some binding like:
<input data-bind="hasFocus: enabled" />
and i want run some function on focus, and other on focus lost( or enabled = true/false) but run when value changes. Any help?
回答1:
You could subscribe to your enabled function, such as:
enabled.subscribe(function(newValue) {
if(newValue) { // Has focus
} else {
// No focus
}
});
回答2:
event: { mouseover: enableDetails, mouseout: disableDetails }
Try this:
<input data-bind="hasFocus: enabled, event: { focus: onFocus, blur: onBlur}" />
if you want to monitor value change you should do it in viewmodel:
this.enabled.subscribe(function(newValue){
//use newValue
});
Note: you have syntax error in viewmodel:
enabled: ko.observable(false); <--
回答3:
Typically, a good solution is to subscribe to your observable and handle your logic there like:
enabled.subscribe(function(newValue) {
if (newValue) {
//do something if it is true
}
else {
//do something if false
}
});
来源:https://stackoverflow.com/questions/18253206/knockout-run-function-on-value-changed