Demian Kasier
Demian Kasier

Reputation: 2523

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

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);
}};

I'd like to get the first one to behave like the second one.

Upvotes: 1

Views: 58

Answers (1)

nemesv
nemesv

Reputation: 139778

Writing toggleContent(this.content) immediately executes your toggleContent function and if it is not returning a function then it breaks the click binding.

So you need to set your registerTClick to a function reference or something which returns a function reference.

In your case you can use the bind method to create a new function from your toggleContent which receives the this.content when it gets called:

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

Demo JSFiddle.

Upvotes: 2

Related Questions