brideo
brideo

Reputation: 151

Working with observable arrays in knockout JS (Magento 2)

I am using Knockout JS to perform some basic price calculations which need to be displayed in my view.

I pass in a key => value array as configuration and then my javascript model does some calculation on the array and updates it.

So I can update the frontend, I am using ko.observableArray().

My template file looks like this:

<span>Price $<span data-bind="text: priceCalculator.prices()['<?php echo $block->getSomeKey ?>']"></span></span>

And my PriceCalculator Model looks like this:

this.priceMap = priceMap; // from config
this.prices = ko.observableArray();
this.setObservablePrices();


this.setObservablePrices = function () {
    var self = this;
    $.each( this.priceMap, function( key, value ) {
        self.prices()[key] = self.doSomePriceCalc(value);
    });

    return this;
};

The problem is, my template only displays the first instance of the variable set in my array. IE if I run this.setObservablePrices(); again and the prices are updated it's not reflected in my template file.

I notice the Knockout JS says to use self.prices().push(value) however I don't know if I can do this without loosing my array keys?

I tried the following but it creates a 3d array which I don't want:

var price = {};
price[key] = value;
this.prices().push(price);

Upvotes: 0

Views: 2588

Answers (1)

brideo
brideo

Reputation: 151

Okay so I figured it out, I had to approach it slightly differently. Rather than using an observable array, I created observable elements in an array:

var self = this;
$.each( this.prices, function( key, value ) {
    self.prices[key] = ko.observable(self.doSomePriceCalc(value));
});


this.setObservablePrices = function () {
var self = this;

    $.each( this.prices, function( key, value ) {
        self.prices[key](self.doSomePriceCalc(value));
    });

return this;
};

Upvotes: 1

Related Questions