Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  96] [ 2]  / answers: 1 / hits: 69973  / 12 Years ago, thu, may 17, 2012, 12:00:00

I have two variables:



var trafficLightIsGreen = false; 
var someoneIsRunningTheLight = false;


I would like to trigger an event when the two variables agree with my conditions:



if(trafficLightIsGreen && !someoneIsRunningTheLight){
go();
}


Assuming that those two booleans can change in any moment, how can I trigger my go() method when they change according to the my conditions?


More From » javascript

 Answers
9

There is no event which is raised when a given value is changed in Javascript. What you can do is provide a set of functions that wrap the specific values and generate events when they are called to modify the values.



function Create(callback) {
var isGreen = false;
var isRunning = false;
return {
getIsGreen : function() { return isGreen; },
setIsGreen : function(p) { isGreen = p; callback(isGreen, isRunning); },
getIsRunning : function() { return isRunning; },
setIsRunning : function(p) { isRunning = p; callback(isGreen, isRunning); }
};
}


Now you could call this function and link the callback to execute go():



var traffic = Create(function(isGreen, isRunning) {
if (isGreen && !isRunning) {
go();
}
});

traffic.setIsGreen(true);

[#85518] Wednesday, May 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yesseniadajab

Total Points: 258
Total Questions: 101
Total Answers: 127

Location: Mexico
Member since Mon, Sep 12, 2022
2 Years ago
;