javascript 为可观察对象设置回调函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12489835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:18:41  来源:igfitidea点击:

setting a call back function for observable objects

javascriptknockout.jsboilerplatejs

提问by Dhananjaya

I'm trying to integrate knockoutJS variables to a Jquery-UI, so to update my UI when a knockout observable changes, I need a way to call a function when observable changes. I want to set my own call back function so if my observable variable changes this call back function need to be called automatically.

我正在尝试将knockoutJS 变量集成到Jquery-UI 中,因此要在敲除的observable 更改时更新我的​​UI,我需要一种在observable 更改时调用函数的方法。我想设置我自己的回调函数,所以如果我的可观察变量发生变化,这个回调函数需要自动调用。

回答by gbs

You can call the subscribefunction on a observable, giving it the callback function to be called when the observable changes.

您可以在 observable 上调用subscribe函数,为它提供在 observable 更改时要调用的回调函数。

<input data-bind="value: val"/>

var Model = function() {
  var self = this;
  this.val = ko.observable();  
  this.val.subscribe(function () {
        alert(self.val());                
  });
};
ko.applyBindings(new Model());