Search code examples
javascriptarraysknockout.jscomputed-observable

How to add an additional array item to a computed observable at runtime


I am trying to append an additional value to a knockout computed observable with no luck. Hopefully someone can point me in the right direction. Currently I am iterating through a collection of fields and building an array of dates

//extract Primary dates from entities
report.PrimaryDateRangeAttributes = ko.computed(function () {
      return $.grep(entity.PrimaryAttributes(), function (item) { return item.DataType() === 'datetime' });
 });

Once I get the array built I wanted to add one additional item

report.PrimaryDateRangeAttributes.push('DateEntered');

However push is not supported on a computed observable. Can anyone provide some suggestions on how to insert the additional value during the initialization of the object?

Thanks in advance,


Solution

  • Since the computation function is called to build the value whenever the value is required (that's the purpose of computed, after all), you simply add that within the function:

    //extract Primary dates from entities
    report.PrimaryDateRangeAttributes = ko.computed(function () {
          var rv = $.grep(entity.PrimaryAttributes(), function (item) { return item.DataType() === 'datetime' });
          rv.push('DateEntered');
          return rv;
    });