SB2055
SB2055

Reputation: 12862

Appending items to a knockout array?

I'm trying to take an observable containing an array (not observableArray, but can change this if needed), and append items of the same type to the array, without doing a foreach and notifying subscribers for each new item pushed.

I've tried a few different methods per posts found on SO and github, but nothing I've tried seems to work. I can replace the contents without any issues - it's just adding items that I've having a problem with.

Fiddle:

http://jsfiddle.net/ckMJE/236/

I also tried this to no avail:

 self.colors.push.apply(self.colors,self.newColors);

Any help would be much appreciated.

Code:

var ViewModel = function () {
    this.self = this;
    self.index = ko.observable(0); // default
    self.newColor = ko.observable("purple"); // default
    self.newColors = ko.observable([{
        color: 'it'
    }, {
        color: 'is'
    }, {
        color: 'working'
    }]);
    self.colors = ko.observable([{
        color: 'red'
    }, {
        color: 'blue'
    }, {
        color: 'yellow'
    }]);
    self.addSome = function () {
        ko.utils.arrayPushAll(self.colors, self.newColors);
    };
    self.replace = function () {
        self.colors(self.newColors());
    };
};
ko.applyBindings(new ViewModel());

Upvotes: 0

Views: 229

Answers (2)

beauXjames
beauXjames

Reputation: 8418

Here ya go...just need to fiddle with your arrays then pass the combined array back over to your observable in question.

http://jsfiddle.net/ckMJE/247/

    self.addSome = function () {
        var oldArray = self.colors(),
            newArray = self.newColors(),
            combinedArray = oldArray.concat(newArray);
        self.colors(combinedArray);
    };

Upvotes: 1

ebohlman
ebohlman

Reputation: 15003

1) You need to unwrap your array, operate on it, and only then set the observable to the altered array:

self.addSome = function () {
    self.newColors(ko.utils.arrayPushAll(self.colors(), self.newColors()));
};

2) Unless your second line of code is a typo, you've inadvertently made self a global, which will cause you lots of trouble if you eventually use nested viewmodels.

Upvotes: 2

Related Questions