Trying to set Observable value inside onValueChanged

I’m trying to do this:

var loginExport = {
cpf: Observable(''),
Test() {
        loginExport.cpf.onValueChanged(module, function (item) {
            loginExport.cpf.value = mask('000.000.000-00', loginExport.cpf.value) // This function returns a String
            console.log(loginExport.cpf.value)
        });
    }
}

When i run the function, and start typing new values, my FuseTools crash. (Mac OSX)

How i can fix it?

I’m trying to replace the Observable value with a new Value, and this value is the result of the mask function.
With this i want to achieve something like a mask on the input.
So, the mask function, process the string and add what i want

e.g :
123.333.444-22

When the onValueChanged is fired, i want to update the value, with the processed string…

Observable notifies its subscribers of a change every time you (or some other code) change its .value. Not just when the value actually changes, but also when it’s replaced by the same value. Meaning, that code of yours ends up in an endless loop as soon as you type the first character.

See if adding a simple if helps things:

loginExport.cpf.onValueChanged(module, function (item) {
	var masked = mask('000.000.000-00', loginExport.cpf.value);
	if (item !== masked) {
		loginExport.cpf.value = masked;
	}
});

A different approach is to hide the TextInput you’re typing in and only output that “masked” string. See our Code input example for an example of that.

Hope this helps!

Right, so that simple if wouldn’t really help on its own, because what we really need to know is if the string has already been masked. If it has, the masking function has to take that into account.

Here’s a complete, minimal and working repro that you can use to understand the thinking behind a potential solution for this challenge:

<App>
	<JavaScript>
	var Observable = require("FuseJS/Observable");
	var cpf = Observable("one");
	cpf.onValueChanged(module, function(x) {
		var mask = "new value: ";
		var isMasked = false;
		if (x.substr(0,11) !== mask) {
			cpf.value = mask + x;
		}
	});
	function changeVal() {
		cpf.value = "two";
	}
	module.exports = {
		cpf: cpf,
		changeVal: changeVal
	};
	</JavaScript>
	<StackPanel>
		<Text Value="{cpf}" TextWrapping="Wrap" />
		<Button Text="Change" Clicked="{changeVal}" />
	</StackPanel>
</App>