View Full Version : how to fire a custom event when variable changes value

30 Aug 2011, 8:49 AM
How can I fire a custom event when a specific variable or object property changes value?

Specifically i would like to watch the value of window.navigator.onLine, fire a custom event which my panels can listen for and work differently depending upon which event was fired.

Any suggestions on how this should be done?

30 Aug 2011, 7:52 PM
Basically you're asking if javascript fires some event when variables are (re-)assigned. The answer is no, but you can implement access controls. You could just wrap the value so it's not public and expose accessor methods (getters and/or setters). You do this with closures. Something like

this.ClientNumberManager = function () {
var clientNum = 3;
return {
getClientNum: function () {
return clientNum;
setClientNum: function (val) {
clientNum = val;

or similar. Then you can debug or fire events or whatever, but you have to go through the closure trick, one way or another, to produce "private" access controls with JS. Otherwise, anyone can set object properties to whatever they like.~o):-?

31 Aug 2011, 5:29 AM
@darthwes - Thanks for the response.

Your solution would work for variable I create, but i want to specifically monitor window.navigator.onLine which is read-only field and changes values when the browser looses connectivity.

Any creative ideas?

31 Aug 2011, 4:03 PM
Oh, I can be creative?

31 Aug 2011, 4:17 PM
Oh, I can be creative?

by all means

31 Aug 2011, 4:22 PM

new Ext.Application({
delayAmount: 500,

launch: function () {
new Ext.Panel({
fullscreen: true,
html: 'Hello World!'

this.currentOnlineState = window.navigator.onLine;
this.myDTask = new Ext.util.DelayedTask(this.pollForChange, this);

this.on('onlineStateChange', this.respondToNewState, this);


pollForChange: function () {
if (this.currentOnlineState !== window.navigator.onLine) {
this.fireEvent('onlineStateChange', window.navigator.onLine);
this.currentOnlineState = window.navigator.onLine;

if (this && this.myDTask) {
this.myDTask.delay(this.delayAmount || 10000);

respondToNewState: function (currState) {
console.log("State Has Changed !!!");
console.log("State is now ", (currState ? "ONLINE" : "OFFLINE"));

Something like that should give you what you want, no? You gots an event, just play with that delayAmount until your happy, I suppose. Need to set up a listener on destroy to stop the thing, etc., but this works for you, yes? ~o):-?

31 Aug 2011, 5:02 PM
yea polling the attribute would work cross browser. thank you!