Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom parameters on knockout click binding

I'm currently trying to call a function with a custom parameter, however I'm unable to access the parameter, and I get back an observable() object instead. Basically what I'm trying to do is to retrieve the index of that specific element in the list. Could someone point me in the right direction on how I could do so?

HTML:

<div id="formula">
  <b>Formula</b><br/>
    <!-- ko foreach: formula -->
      <span data-bind="text: $data, attr: {name: $index}, click: $parent.convert.bind($data,$index)"></span><br/>
    <!-- /ko -->
</div>

Javascript:

var ListModel = function(formula) {
  var self = this;
  self.formula = ko.observableArray(formula);
  self.convert = function(index) {
    alert(index); //this should show the index of the clicked element
  }
};

listModel = new ListModel(formula);
ko.applyBindings(listModel);
like image 508
Wei Hao Avatar asked Feb 21 '23 05:02

Wei Hao


1 Answers

Should be $parent.convert.bind($data,$index())

<div id="formula">
  <b>Formula</b><br/>
    <!-- ko foreach: formula -->
      <span data-bind="text: $data, attr: {name: $index}, click: $parent.convert.bind($data,$index())"></span><br/>
    <!-- /ko -->
</div>

Example

like image 192
Serhiy Avatar answered Mar 03 '23 16:03

Serhiy