淘汰赛,为什么不;我的功能在点击事件时启动

Knockout, Why doesn't my function fire on the clickevent?

本文关键字:事件 启动 功能 为什么不 我的 淘汰赛      更新时间:2023-09-26

HTML:

<div data-bind='click: registerClick'>
  <img src="image.png" width="450px" />
</div>
<div data-bind='visible: content'>
  content
</div>

Javascript:

this.content = ko.observable(false);
//Named function triggers at the start 
//(after pressing f5, and doesn't trigger when I click the image)
this.registerTClick = toggleContent(this.content);
//unamed function only triggers at the clickevent.
this.registerClick = function () {
if (this.content() == false) {
  this.content(true);
}};

我想让第一个表现得像第二个。

编写toggleContent(this.content)会立即执行toggleContent函数,如果它没有返回function,则会中断单击绑定。

因此,您需要将registerTClick设置为函数引用或返回函数引用的内容。

在您的情况下,您可以使用bind方法从toggleContent创建一个新函数,该函数在调用时接收this.content

this.registerTClick = toggleContent.bind(this, this.content);

演示JSFiddle。