2

Is there a way to detect if an global Boolean values changes from false to true with jQuery?

Philip
  • 6,827
  • 13
  • 75
  • 104

3 Answers3

8

Yes, use a getter/setter pair of which the setter traps the setting of the variable: http://jsfiddle.net/M768B/.

(function() {
    var val = false;

    ​Object.defineProperty(window, "something", {
        get: function() {
            return val;
        },
        set: function(v) {
            val = !!v; // `!!` to force setting a boolean
            alert("Changed to " + val);
        }​​
    });
})();
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

The solution might be

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Object - watch () method example</title>
</head>
<body>
<h1 style="color: red">JavaScript Object : watch() method</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ o = {x:10}
o.watch("x",
function (id,oldvalue,newvalue) {
document.writeln("o." + id + " changed from "
+ oldvalue + " to " + newvalue+"<br />")
return newvalue
})
o.x = 20
o.x = 30
o.x = 40
//]]>
</script>
</body>
</html> 

Compatible with:

  • Internet Explorer 7
  • Firefox 3.6
  • Google Chrome 7
  • Safari 5.0.1
  • Opera 10

Seen here.

thomas
  • 2,580
  • 1
  • 22
  • 28
  • It's customary on this site to not just post a link, but also include the code and details in your answer so that it stands on its own. Should the link break, your answer would still have value to the community and would stand on it's own. Use the `edit` link to continue to improve your answer. :) – jamesmortensen Mar 11 '12 at 16:45
  • One thing to point out, watch only works on Mozilla, and according to the docs, has a performance impact. They recommend it for debugging. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch – jamesmortensen Mar 11 '12 at 16:55
0

Keep an array of function callbacks as "observers". When anything changes the Boolean through your interface function (e.g. setBooleanValue(True); ) then iterate through the callback array and call each function to notify the observers.

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96