monitoring idle state
by Seungrae Lee
HTML
<div id="bd-wrapper">
<p style="opacity:0.2">이 데모화면은 jQuery plugin을 이용해 만든 모니터 클래스입니다. 일정시간이 지난후 이벤트가 발생하지 않으면 idle상태로 간주합니다.</p>
<div id="debug">let's see...</div>
</div>
CSS
body {
background: #555;
}
#bd-wrapper {
width: 720px;
margin: 1em auto;
background: #333;
color: #fdd;
padding: 1em;
}
p {
color: #aaf;
font: 1em/1.5 Georgia, serif;
}
a {
color: #aaf;
}
JavaScript
(function ($) {
$.extend($.fn, {
monitor: function (options) {
return this.each(function () {
$.creator(this, options);
});
}
});
// instance creator
$.creator = function (target, options) {
// check if a monitor was already created
if (target.monitor) {
target.monitor.init();
} else {
target.monitor = new $.monitor(options, target);
} //if~else
return target.monitor;
};
// constructor for monitor
$.monitor = function (options, target) {
this.o = $.extend(true, {}, $.monitor.defaults, options);
this.target = target;
this.init();
};
$.extend($.monitor, {
defaults: {
timeout: 500,
events: [scroll]
},
setDefaults: function (settings) {
$.extend($.monitor.defaults, settings);
},
prototype: {
init: function () {
this._idleTime = null;
this._timer = null;
this._state = "on";
this.idleTime = null;
// add event listener
this.initObservers(this.target, this.o.events);
this.setTimer(this.target);
},
initObservers: function (target, events) {
var self = this;
$.each(events, function (i, e) {
$(target).bind(e, function (event) {
self.onInterrupt(target, event);
});
});
},
onInterrupt: function (target, event) {
this.idleTime = new Date() - this._idleTime;
$(target).bind("state:active", function () {}).trigger("state:active", $.monitor.onActive(this.idleTime));
this.setTimer(target);
},
setTimer: function (target) {
clearTimeout(this._timer);
...