.onvaluechanged use

Hi Im wondering if this use of an .onvaluechanged is legitimate and works as intended

var amount = Observable();
var buttonEnabled = Observable(false);

amount.onValueChanged(null, function() {
    if(parseInt(amount.value) >= 1000){
        buttonEnabled.value = true;
    }else{
        buttonEnabled.value = false;
    }
});

where amount is bound to an input from ux, and buttonEnabled is a button only enabled when the value is over a certain value

    <TextInput Value="{amount}" />

It works, I’m just wondering if youre suppost to use the listner like this, since the onvaluechanged is suppost to listen for changes in a module. Here I am trying to listen for changes in the observable.

Maybe there is some other logic that makes more sense?

Hi Paul,

the approach in general looks legit, although there are some minor things that should be done differently:

var amount = Observable(0);
var buttonEnabled = Observable(false);

amount.onValueChanged(module, function(x) {
    if (parseInt(x) >= 1000) {
        buttonEnabled.value = true;
    } else {
        buttonEnabled.value = false;
    }
});

Note that you get the new value of amount observable in the x parameter every time there is a change to it.

Also, make sure you always put the first parameter exactly as module - it ties the subscription to the lifecycle of the JS file you’re currently in (it is the same module as in module.exports). Otherwise you risk leaking memory.

but couldnt I listen for changes in a different module?

Paul, I think you have misunderstood how .onValueChanged works. Or the module bit.

The module there is only to bind the lifecycle of that subscription (.onValueChanged adds a subscriber to the Observable) to that particular JS file. So when you, say, navigate away from the page where you use it, the subscriber would also be killed, so that it doesn’t stay lingering around and eating memory in background.

obs.onValueChanged does listen to the changes of that Observable. And that’s all it does.

Oh! ok thank you for the thorough explaination