Search code examples
knockout.jsknockout-2.0knockout-validationknockout-3.0

Change in observable array in side observable array not updating UI in knockout js


var subject = function (data) {
  self = this;
  self.subjectName = ko.observable(data ? data.subjectName : "");
  self.subjectPassPercentage = ko.observable(data ? data.subjectPassPercentage : "");
}

var course=function(data){
  self = this;
  self.courseName = ko.observable(data ? data.courseName : "");
  self.subjectList = ko.observableArray([]);
}

view modal

app.viewmodal = (function (ko) {
  "use strict";
  var me = {
    subjectObject: ko.observableArray([]),// Array of subject
    course: ko.observableArray([])// Array of course
  }
  return me;
  })(ko);

on click, I am executing below code

me.course()[0].subjectList().push(me.subjectObject()[0]);

and in HTML I am trying to print the count

<div data-bind="text:viewmodal.course()[0].subjectList().length"></div>

But the change in the array subjectList is not reflecting in UI. It is always showing 0.

But when I click below div then it gives the correct count in the console log.

<div  data-bind="click: function(){ console.log(viewmodal.course()[0].subjectList().length)}">Click Me</div>

Please help me in identifying the problem and suggest me the solution.


Solution

  • The problem here seems to be that code:

    me.course()[0].subjectList().push(me.subjectObject()[0]);
    

    Calling .subjectList().push(...) unwraps array in observable and push object directly into it - by doing that you are bypassing all ko mechanisms. Documentation says:
    pop, push, shift, unshift, reverse, sort, splice All of these functions are equivalent to running the native JavaScript array functions on the underlying array, and then notifying listeners about the change

    So to fix this you just need to remove parenthesis when calling push on your observableArray like that:

    me.course()[0].subjectList.push(me.subjectObject()[0]);
    

    That will notify ko about your changes and UI should be updated