SteveSanderson / knockout-es5

Knockout.js meets ECMAScript 5 properties
158 stars 39 forks source link

Recalculation Never Happens in a Nitch Case #55

Open josiahbryan opened 8 years ago

josiahbryan commented 8 years ago

Cart.productDataPending in the example below is never recalculated even when the "referenced" observable, CatLine.productDataPendingFlag, is changed.

Am I doing something wrong? Should I be doing this something different?

` var CartLine = function(rawLine) { if(!rawLine) rawLine = { quantity: 1, quantity_packed: '', productid_raw: 0, productid: '', price: '', };

    var self = this;

    for(var key in rawLine)
        self[key] = rawLine[key];

    // ............

    self.productDataPendingFlag = '';

    // Instead of declaring ko.observable properties, we just have one call to ko.track 
    ko.track(this);

    ko.getObservable(this, 'productid_raw').subscribe(
        function(newValue) {
            //console.log("productid changed:", newValue);

            self.productDataPendingFlag = 'product-data-loading';

            $.ajax({
                url: '/office/inventory/api/query',
                data: {
                    type: 'all',
                    productid: newValue,
                    patientid:
                        window.NCSData.patientid ? 
                        window.NCSData.patientid : 1
                },
                success: function(data) {
                    self.productDataPendingFlag = '';
                    self.price = data.price;
                },

                error: function(result) {
                    self.productDataPendingFlag = '';
                    alert("Error: "+result.resultText);
                },
            });
        });
};

var Cart = function() {
    // Stores an array of lines, and from these, can work out the grandTotal
    var self = this;

    var convertedLines = $.map(initialData, function(line) { return new CartLine(line) } );
    if(!convertedLines.length)
        convertedLines.push(new CartLine());

    // ............

    self.productDataPendingFlag = function() {
        var isPending = false;
        console.log("Cart.productDataPendingFlag: recalculating...");
        self.lines.forEach(function(line) {
            if(line.productDataPendingFlag)
                isPending = true;
        });

        return isPending ? 'product-data-loading' : '';
    };

    // ............

    // Instead of declaring ko.observable properties, we just have one call to ko.track 
    ko.track(this);
};

ko.applyBindings(window.viewModel = new Cart());

`

jmvtrinidad commented 7 years ago

If your self.lines in Cart is obseravbleArray and your line.productDataPendingFlag in CartLine through ko.track. productDataPendingFlag should change for any change in tyour self.lines.