我正在尝试实现一些空闲检测代码。我可以使用其他一些帖子,但是我希望它成为聚合物元素的一部分,因此我可以将<idle-fire></idle-fire>
粘贴在我的应用中的任何地方并传递一些参数。这是我拥有的:
<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="idle-fire">
<script>
Polymer({
is: 'idle-fire',
properties: {
idlelimit: {
type: Number,
value: 10
}
},
ready: function() {
}
});
</script>
</dom-module>
<script>
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
console.log("tick (" + idleTime + ")");
if (idleTime >= 2) { // in minutes
console.log("Idle event fired!")
}
}
</script>
如果我尝试将<script>
标签的任何部分移至聚合物ready
功能,则无法正常工作。并以此方式,我无法访问idlelimit
属性。
任何方向都赞赏。
如果我尝试将
<script>
标签的任何部分移至聚合物ready
功能,则无法正常工作。并以此方式,我无法访问idlelimit
属性。
设置回调时,您可能不会正确绑定上下文(即this
)。如果您完全忘记这样做,则计时器回调的上下文将是外部上下文(Window
对象),而不是您的聚合物对象,其中idlelimit
可用。
这是设置timerIncrement
回调上下文的一种方法:
// in Polymer object
setupTimer: function() {
setInterval(timerIncrement.bind(this), 1000);
}
另外,您可以使用ES6箭头功能自动为您绑定上下文:
// in Polymer object
setupTimer: function() {
setInterval(() => {
this.idleTime++; // `this` is Polymer object
}, 1000);
}
这是该代码转换为聚合物:
HTMLImports.whenReady(() => {
Polymer({
is: 'idle-fire',
properties: {
idlelimit: {
type: Number,
value: 10
}
},
attached: function() {
// Increment the idle time counter every second.
this._idleInterval = setInterval(this._timerIncrement.bind(this), 1000);
this._idleTime = 0;
// Zero the idle timer on mouse movement or keypress.
document.onmousemove = () => { this._idleTime = 0 };
document.onkeypress = () => { this._idleTime = 0 };
},
detached: function() {
clearInterval(this._idleInterval);
},
_timerIncrement: function() {
const idleTime = ++this._idleTime;
console.log("tick (" + idleTime + ")", this.idlelimit);
if (idleTime >= this.idlelimit) { // in seconds for this demo
console.log("Idle event fired!");
clearInterval(this._idleInterval);
}
}
});
});
<head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<div>See timer in DevTools console</div>
<div>Move your mouse over this document, or press any key to restart the timer</div>
<idle-fire></idle-fire>
</body>
codepen
fyi:您可能会考虑使用已经可用的<f-idlejs>
元素。