1
votes

In my ViewModel, I have an observable array and one element of this array can be the selected element:

var ViewModel = function () {

// the array
this.fruits = ko.observableArray([{
    name: "apple"
}, {
    name: "orange"
}, {
    name: "banana"
}]);

// the selected element
this.selectedFruit = null;

};

ko.applyBindings(new ViewModel());

Now I show the elements in a list:

<div data-bind="foreach: fruits">
<ul>
    <li href="" data-bind="text: name "></li>
</ul>

Now i want that a click on one item selects the selected fruit in my ViewModel. What is the KnockoutJS-way to do so? How can I make a function to reference back to the fruit in the foreach-loop?

1

1 Answers

1
votes

You need to get back to the parent to execute the method because your current scope is inside the fruit array. The code would look like this:

<div data-bind="foreach: fruits">
<ul>
    <li href="" data-bind="text: name, click: $parent.fruitWasClicked"></li>
</ul>
</div>


this.fruitWasClicked = function(fruit){
//do something here
}

Here is some documentation further explaining the context http://knockoutjs.com/documentation/binding-context.html