dojo.declare("my.IdleListener", [], {
_mouseMoveHandle: null,
_keyDownHandle: null,
_timeout: 30000,
isRunning: function() {
return this._enabled;
},
isIdle: function() {
return this._idle;
},
start: function(newTimeout) {
this._enabled = true;
this._idle = false;
if (typeof newTimeout == "number") {
this._timeout = newTimeout;
}
this._mouseMoveHandle = dojo.connect(dojo.doc, "onmousemove", this, "_handleUserEvent");
this._keyDownHandle = dojo.connect(dojo.doc, "onkeydown", this, "_handleUserEvent");
// set a timeout to toggle state
this._idleTimeout = setTimeout(dojo.hitch(this, "_toggleIdleState"), this._timeout);
},
stop: function() {
this._enabled = false;
// clear any pending timeouts
clearTimeout(this._idleTimeout);
// detach the event handlers
dojo.forEach([this._mouseMoveHandle, this._keyDownHandle], function(item, index, array) {
if(item) {
dojo.disconnect(item);
}
});
},
_handleUserEvent: function() {
// clear any existing timeout
clearTimeout(this._idleTimeout);
if (this._enabled) {
// if the user is just waking us up again, toggle the idle state.
// otherwise, reset the timeout with a new timeout
this._idle ? this._toggleIdleState() : this._idleTimeout = setTimeout(dojo.hitch(this, "_toggleIdleState"), this._timeout);
}
},
_toggleIdleState: function() {
this._idle = !this._idle;
this._idle ? dojo.publish("idle", []) : dojo.publish("active", []);
}
});
To start your idle handler with a default timeout of 30 seconds, all you need to do is:
var idleListener = new my.IdleListener();
idleListener.start(30000);
Then in whatever parts of your application deal with polling network resources, all you need to do is:
dojo.subscribe("idle", function() {
});
dojo.subscribe("active", function() {
});
For jQuery users, Paul Irish has ported the code. too.
Just posted an update of this code to github. Check it out!
No comments:
Post a Comment