简体   繁体   中英

How to use current object in a computed observable? — Knockout.js

I have a foreach data-binding on an array.

I want to access the current object or place in the computed observable (as it happens with the click data-binding).


Example:

Here is my View:

 <tbody data-bind='foreach: items'> <tr data-bind="attr: {class:$root.changeClass()}"> <td data-bind='text: name'></td> </tr> </tbody> 

And, here is the view-model:

 function model() { var self = this; self.items = ko.observableArray(itemArray); self.changeClass = ko.computed(function(data) { //code that depends on data return 'someClass'; }); }; 


I'm a beginner. Please help. Thanks in advance.

Try something like this

View:

<table data-bind='foreach: items'>
  <tr data-bind="attr: {class:$root.changeClass($data)}">
    <td data-bind='text: $data'></td>
  </tr>
</table>

Css :

 .classEven{
     color:blue;
    }

 .classOdd{
       color:red;
    }

viewModel:

function model() {
  var self = this;
  self.items = ko.observableArray([1,2,3]);
  self.changeClass =function(data) {
    //code that depends on data
      if(data%2) return 'classEven';
      else return 'classOdd';
  };
};

ko.applyBindings(new model()); // This makes Knockout get to work

working sample fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM