Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding an array to a view model using knockout.js

is there a way to define an array and bind it to a view model? or does it have to be defined as an object?:

---- js ----

var arr = [{"id":"1","desc":"1","enabled":true,"tabStr":"/2 * * * * * *"},
            {"id":"2","desc":"2","enabled":true,"tabStr":"1-60/2 * * * * * *"},
            {"id":"3","desc":"3","enabled":false,"tabStr":"/5 * * * * * *"}];

$(document).ready(function(){
  ko.applyBindings(arr);
});

----- html ----

    <tbody data-bind="foreach: ???">
      <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: desc"></td>
        <td data-bind="text: tabStr"></td>
        <td data-bind="text: enabled"></td>
      </tr> 
    </tbody>
like image 325
zcaudate Avatar asked Apr 26 '26 23:04

zcaudate


1 Answers

If you don't want to wrap your array in an object, then you can use the special context variable $data (or $root since this is the top-level view model) to bind against the current data. So, your binding would look like:

<tbody data-bind="foreach: $data">
  <tr>
    <td data-bind="text: id"></td>
    <td data-bind="text: desc"></td>
    <td data-bind="text: tabStr"></td>
    <td data-bind="text: enabled"></td>
  </tr> 
</tbody>

You can find more information about the context variables here: http://knockoutjs.com/documentation/binding-context.html

like image 110
RP Niemeyer Avatar answered Apr 28 '26 11:04

RP Niemeyer