KnockOut run function on value changed

泄露秘密 提交于 2019-12-23 07:39:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!