jspence
jspence

Reputation: 429

Knockout Foreach Javascript function

Is it possible to declare a javascript function in your knockout foreach binding? I want to generate a list from a javascript function outside of my view model.

 <select class="form-control" data-bind="foreach: { data: function() { // return list values } }">
 <option data-bind="text: Value, attr: { value: Value }"></option>
            </select>

Upvotes: 0

Views: 844

Answers (1)

Origineil
Origineil

Reputation: 3118

No quite sure what you are trying to achieve with <option data-bind="text: Value, attr: { value: Value }"></option>.

Have a look at my fiddle for a few different setups. It contains usages of both options and foreach bindings on a select element.

To answer the question, you provide a function in your viewModel to provide the desired data. As long as your viewModel can "access" the data, the function will provide it to the binding. If the data were to be a simple list of literals, then all that is required :

Javascript:

var listOfLiterals = function() { return  ["One", "Two", "Three"] };

  var viewModel = {
     selectedLiteral: ko.observable(),  
     getLiterals: function() {
       return listOfLiterals();
  }
}

HTML:

<select data-bind="options: getLiterals(), value: selectedLiteral"></select>

Upvotes: 1

Related Questions