0

I am looping items within a foreach statement. On page load, by default I am selecting the first item (data-bind="css: { selected: $index() == 0 }"):

var viewModel = function(){
 var self = this;
 self.pattern_index = 0;
 self.select = function(data) {
  //handle click
 };
 self.makes = [
  {id:1, name: 'Northwoods Prestige'},
  {id:2, name: 'Forest Bay'},
  {id:3, name: 'Timberland'}
 ];
};
var model = new viewModel();
ko.applyBindings(model);

HTML:

  <div class='oTitle'><span class="label label-primary">Patterns</span></div>
  <div data-bind="foreach: makes">
      <div data-bind="css: { selected: $index() == 0 }, click: $root.select.bind($data)">xx </div>
  </div>

CSS:

.selected{background-color:red;}

My question is how to make other items selectable, selecting the clicked item (.selected) and removing selectable class from first item

jsfiddle: http://jsfiddle.net/diegopitt/g57qs9a7/

Diego P
  • 1,728
  • 13
  • 28
  • if i am not wrong you posted one such question yesterday i answered that (check the comments) . cheers – super cool Jun 19 '15 at 03:11
  • @supercool Seems the OP is asking a very similar series of questions. http://stackoverflow.com/questions/30926278/passing-index-and-data-as-arguments-to-function-for-click-handler – CrimsonChris Jun 19 '15 at 04:52
  • @CrimsonChris ha true via different accounts lol . – super cool Jun 19 '15 at 04:54

1 Answers1

1

Have a selectedIndex observable that can be used in the css binding to determine if a row is "selected".

Example: http://jsfiddle.net/Lgn4ppwo/

HTML

<div data-bind="foreach: makes">
    <div data-bind="css: { selected: $index() === $root.selectedIndex() }, click: $root.select.bind($root, $index())">xx </div>
</div>

View Model

function ViewModel() {
    this.selectedIndex = ko.observable(0);
    this.select = function(index) {
        this.selectedIndex(index);
    };
    ...
};
CrimsonChris
  • 4,651
  • 2
  • 19
  • 30
  • thank you! It is working. I have one more question I need to pass $data to the function select. What are we passing in $root ? I see we are passing 2 parameters to the select function but it is expecting one which is index ... – Diego P Jun 18 '15 at 20:46
  • @DiegoP You should look at how `bind` works. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – CrimsonChris Jun 18 '15 at 21:14