.onvaluechanged listner

In this code untill i log total.value the value is not updated in the ux

total.onValueChanged(Context.js, function() {
    Context.cart.forEach(function(item) {
        total.value += parseFloat(item.price) * parseInt(item.amount);
        console.log(total.value + "  !!!!");
    });
});
    console.log(total.value + "  !!!!"); 

ux code is this


<Receipt.Detail Label="TOT. PRIS" LabelValue="{total},-" LabelColor="Orange" >

Also if I make changes to the Context.cart it still does not update, unless I do a new console.log and save. How do I make it listen properly?

Hi Paul,

it’s a bit challenging to understand what could be wrong with just the snippets you pasted. The fact that it starts working when you add a console.log seems alarming.

The only suspicious thing I see is that you’re changing the total.value from within total.onValueChanged(), which by itself looks like a feedback loop.

It would be great if you could show a complete reproduction, preferably a small one. Also, please include the Fuse version, OS you’re on and the target you’re testing (local, Android, iOS?).

Hey Uldis,

Im sorry I wont be able to reproduce the issue, however I realized changing the total.value from within total.onvaluechanged was a bad time so I changed it and now it works perfect.

Thanks!

var total = Observable(0);

Context.cart.onValueChanged(Context.js, function() {
    total.value = 0;
    Context.cart.forEach(function(item) {
        total.value += parseFloat(item.price) * parseInt(item.amount);
        console.log(total.value + "  !!!!");
    });
});
    console.log(total.value + "  !!!");

Great to hear it worked out, Paul!

If I may suggest a little alteration, it would be this:

var total = Observable(0);

Context.cart.onValueChanged(Context.js, function() {
    var subtotal = 0;
    Context.cart.forEach(function(item) {
        subtotal += parseFloat(item.price) * parseInt(item.amount);
        console.log("SubTotal: " + subtotal);
    });
    total.value = subtotal;
    console.log("Total: " + total.value);
});

This is to avoid setting the total.value to zero and then changing it multiple times. Each of those operations would notify all subscribers of that Observable of the change. This way, you replace the total.value only once the new value is calculated.