简体   繁体   中英

knockout css binding within foreach based on user input

I have a table like below. the user is supposed to type the address info into the third column. If it's empty, then I added a styling

 <tbody data-bind="foreach: people">
      <tr>
          <td data-bind="text: id"></td>
          <td data-bind="text: name"></td>
           <td><input type="text" style="width:100%"  data-bind="css:{warningStyle: address.length == 0 }, value: address"/></td>

          </tr>                                   
 </tbody>

To test it, Here's my code about people in js

people = ko.observableArray([{id:'1', name:'a1', address:'aaa'},{id:'2', name:'a2', address:''}])

When I first load the page, it works as supposed. the 1st person has no styling applied and the 2nd person has the styling (because the address is empty).

Now it I type some address for the 2nd person, it still has the css style applied. My question is why? Shouldn't it has the css style removed becasue the address is not empty anymore? How do I fix this?

That happened because address property is not observable. You can fix it using mapping plugin or without it in next way

var data = [{id:'1', name:'a1', address:'aaa'},{id:'2', name:'a2', address:''}];

function Item(id, name, address) {
    this.name = ko.observable(name);
    this.id = ko.observable(id);
    this.address = ko.observable(address);
}

//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(data, function(item) {
    return new Item(item.id, item.name, item.address);
});

ko.applyBindings(mappedData);

JSFIDDLE

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