Kippie
Kippie

Reputation: 3820

knockout.js: No concat on observableArray

Only starting with knockout.js, but already running into some trouble when trying to make a computed method based on 2 different observableArrays

Using the documentation on knockout.js' website, I've created the following viewmodel:

var Cart = function() {
  var self = this;

  self.Products = ko.observableArray([]);
  self.Products2 = ko.observableArray([]);
  self.Messages = ko.observableArray([]);

  self.TotalAmount = ko.computed(function() {
    var result = 0;
    ko.utils.arrayForEach(
      this.Products().concat(this.Products2()),
      function(item) {
        result+=item.AmountIncludingVAT();
      }
    );
    return result;
  });
};

Doing this throws an error of "Uncaught TypeError: Object #<error> has no method 'concat'.

I know there is this function called arrayPushAll, but it's a destructive function which would alter the original observableArray. (I don't think this is something I want).

Is there any clean way to achieve what I'm trying to do? Or do I have to make 2 different calls to arrayForEach, one for each array?

Upvotes: 2

Views: 10015

Answers (2)

rab
rab

Reputation: 4144

concat didn't works for me .. I did push

self.Products.push.apply( 
  self.Products, self.Products2()
);

Upvotes: 6

Richard Dalton
Richard Dalton

Reputation: 35803

Change:

this.Products().concat(this.Products2()),

to:

self.Products().concat(self.Products2()),

Inside your TotalAmount ko.computed function.

this in the context of your computed refers to the global object rather than the view model. So you need to use the self variable that is assigned the correct this value earlier.

Working Example - http://jsfiddle.net/55kZp/

Upvotes: 6

Related Questions