Search code examples
javascriptjqueryprocedural-programming

Javascript - How do I update variable after it's been set procedurally?


I have a variable defined at the top of my function and a JSON object referencing that variable directly beneath that. A click event, a few loops and an anonymous functions later I update the value of the first variable then reference the JSON object's property expecting it to have the new value, but this does not work.

My code looks something like this:

var errorval = "Not set";
var rules = {
    firstRule : {
        name : 'example',
        message : 'Needs to be '+errorval+' characters long'
    }
}
$('.button').on('click', function(){
    for(var foo in bar) {
        $.each(foo, function(){
            errorval = 3;
            // ALERTS "Needs to be Not set characters long"
            alert(rules.firstRule.message);
        });
    }
});

So I'm asking how I can update errorval at this point in my code so that the rules object has that new value in the message property.


Solution

  • This might solve your issue

    var errorval = "Not set";
    var rules = {
        firstRule : {
            name : 'example',
            getMessage : function() {
              return 'Needs to be '+errorval+' characters long';
            }
        }
    }
    $('.button').on('click', function(){
        for(var foo in bar) {
            $.each(foo, function(){
                errorval = 3;
                // ALERTS "Needs to be Not set characters long"
                alert(rules.firstRule.getMessage());
            });
        }
    });
    

    Instead of a string property, you call the getMessage method which returns a string based on the current value of errorval