2
votes

How can I bind data from a function inside a KnockoutJS foreach ?

e.g. I have the following code:

 <div data-bind="foreach: timeEntries">
     <a href="#page1" data-icon="refresh" data-theme="c">
         <span data-bind="text: getActivityName(ActivityId)"></span>
     </a>

I want to call the function getActivityName which exists in the model context, and pass the ActivityId which is a property on the timeEntry that the foreach iterates over.

Just binding this

data-bind="text: ActivityId"

Will display the activity Id for each row correctly, but I need to do a lookup and get the name from a dictionary. I do get that the code above most likely calls getactivityname on the current item and not on the context, so how do I fix it?

1

1 Answers

6
votes

The foreach binding creates a new bindingcontext (which allows you to bind directly to properties on the items in the loop. If you want to reference a property from the viewmodel instead of the loop, you can use the $root or $parent bindings.

<span data-bind="text: $root.getActivityName(ActivityId)"></span>

The getActivityName function can do the look up for you.

Another option would be to make the objects that are iterated in the foreach observable and create a computed observable that does the look-up for you.