Question

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.

Était-ce utile?

La 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

Autres conseils

this is another solution,please read comments:

var errorval = "Not set";
set(errorval);
$('.button').on('click', function(){
    //for(var foo in bar) {
    //    $.each(foo, function(){
            errorval = 3;
            // you must recall set(errorval) at here for uodate rules object
            alert(rules.firstRule.message);                            
    //    });
    //}
});


function set(errorval){
  rules = {
    firstRule : {
        name : 'example',
        message : 'Needs to be '+errorval+' characters long'
    }
  }
}

Demo

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top