如何在函数中设置一个可观察对象

How to set an observable inside a function?

本文关键字:一个 对象 观察 函数 设置      更新时间:2023-09-26

我试图传递一个可观察到的函数。

function toggleContent(switcher) {
  if (switcher == false) {
    alert(switcher); //this shows the value
    switcher(true);  //this creates an error
    switcher = true; //this doesn't do anything
  }
}
this.content = ko.observable(false);
this.registerClick = toggleContent(this.content());

你需要传递可观察对象本身,你目前只传递它的值。使用

this.registerClick = toggleContent(this.content);
不是

this.registerClick = toggleContent(this.content());

如果将"registerClick"绑定到事件,则不要传递任何值。

this.registerClick = function(){
    console.log(arguments); // you can get anything expected.
};

希望能有所帮助。