Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
Kippie Avatar asked Dec 02 '25 04:12

Kippie


2 Answers

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/

like image 66
Richard Dalton Avatar answered Dec 04 '25 18:12

Richard Dalton


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

self.Products.push.apply( 
  self.Products, self.Products2()
);
like image 30
rab Avatar answered Dec 04 '25 16:12

rab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!