Goran
Goran

Reputation: 93

Knockout VIewModel triggers function inside foreach

I am fighting with strange issue and i am running out of ideas.

The problem is that my view model is triggering function inside foreach on click. So in this case if i click on div menuConnections testcall function is being triggered. Even if i send other value to testcall (such as div id) same value is being sent when I click on menuConnections.

How to stop this and force testcall to be executed only when i click on TheDivWhoCalls?

function ProfileViewModel(userId) {
    var self = this;
  
    self.connectionRequests = ko.observableArray();

  self.getConnections = function () {
        $("#menuConnections").css({ "display": "block" });
    
    //other code which returns data
    };
  
  self.testcall = function(data) {
        alert(target);
    };;
    
  }
<div id="menuConnections" data-bind='click: getConnections'>Connections</div>

<div id="connections" style="display: none">
  
  <div data-bind="foreach: connectionRequests">
    
    <div id="TheDivWhoCalls" data-bind='click: $root.testcall("asd")'><img src="~/Resources/Images/yesIcon.png" /></div>
    
  </div>
  
</div>

Upvotes: 1

Views: 471

Answers (2)

Tuan
Tuan

Reputation: 5412

You might need the bind syntax instead. Try data-bind="$root.testcall.bind($data, 'asd')"

Upvotes: 0

George Mauer
George Mauer

Reputation: 122172

I can't tell for sure without seeing an actual running example with ko.applyBindings but try changing

data-bind='click: $root.testcall("asd")

to

 data-bind='click: $parent.testcall.bind($parent, "asd")

Explanation:

First I changed $root to $parent. I don't know what your $root is, but its safe to assume that your $parent is the VM with the testcall method.

More importantly, is that click: expects a function, but $root.testcall("asd") invokes the function returning undefined. Instead we use Function.prototype.bind to create a new function from testcall with the parameter set to "asd"and this set to $parent

Upvotes: 2

Related Questions