ObservableArray does not reflect data update

I am building an application using the very smooth KnockoutJS library, but I ran into a problem. On the html page, I have a simple control <select>that I want to load with the JSON data returned from the web service.

I define the observed array as follows:

var laborRow = function () {
    this.positions = ko.observableArray([]);
};

When the page loads, an ajax call is made and the data is returned. In the callback, I do the following:

    success: function (msg) {
        laborRow.positions = msg;
    }

based on KO docs, I would expect that I would set the result as follows:

laborRow.positions(msg);

However, this simply raises an error indicating that "laborRow.positions in not a function"

The template in html is as follows:

<tbody data-bind='template: {name: "laborRowTemplate", foreach: laborLine}'> </tbody> 
</div>
  <script type="text/html" id="laborRowTemplate"> 
        <tr>

          <td><select data-bind='options: positions, optionsText: "Title", optionsCaption: "select", value: selectedPosition '></select></td>

        </tr>
    </script>

laborRow ViewModel, . - . , , , . , .

.

:

var laborRow = function () {
    this.positions = ko.observableArray([]);    
};

var projectEstimate = function () {
    this.laborLine = ko.observableArray([new laborRow()]);

};

var projectViewModel = new projectEstimate();
ko.applyBindings(projectViewModel);

//and the code in the callback function on ajax success

 success: function (msg) {
                laborRow.positions = msg;
                //laborRow.positions(msg); **this does not work - error is laborRow.positions is not a function**
            },

html:

 <tbody data-bind='template: {name: "laborRowTemplate", foreach:
laborLine}'> </tbody>

  <script type="text/html" id="laborRowTemplate">
        <tr>
          <td><select data-bind='options: positions, optionsText:
"Title",  optionsCaption: "select", value: selectedPosition '></
select></td>

        </tr>
    </script> 

, , , :

success: function (msg) {
    projectViewModel.laborLine()[(projectViewModel.laborLine().length-1)].positionList(msg);
}
+5
1

, :

var laborRow = function () {
    this.positions = ko.observableArray([]);
    // will only be called if you call var some_var = new laborRow()
};

( ):

var laborRow = {
    positions: ko.observableArray([])
};

laborRow.positions(msg); .


laborRow - . var laborRow - (, ajax), , :

projectViewModel.laborLine()[0].positions() 
// This will return the array you're looking for.
// The key is that laborLine is a `getter` not an attribute

" ko - getters not attributes" ... , ?

+5

All Articles