我需要继续在mousedown
上调用一个函数,我有以下代码:
<button id="zoomin" type="button" {{action "zoomIn" on="mouseDown" target="view" }} class="btn">
<i class="icon-zoom-in"></i>
</button>
但只有在鼠标停止时才调用它,我希望在鼠标启动之前重复调用它。
除了timer
之外还有其他解决方案吗?
答案 0 :(得分:2)
我建议使用mousemove
代替mousedown
。只要鼠标移动,这将重复调用您的函数,而无需设置计时器。当然,如果您希望即使鼠标静止也能定期调用该函数,这将无效。
如果您使用mousemove
,则必须处理涉及无意义的小动作的大量事件。因此,您可能希望“去抖动”事件,过滤掉非常小的动作和非常频繁的事件,如下所示:
const DELTA = 5; // only report moves of greater than five pixels
const DELTA_TIME = 100; // only report moves every 100ms
export default Ember.Component.extend({
// Remember previous coordinates and time.
lastX: null,
lastY: null,
lastTime: null,
// Set up `this.mousemove` so it's bound property.
bind() { this.mousemove = this.mousemove.bind(this); }.on('init'),
// Set up and tear down event listeners.
mousedown() { this.get('element').addEventListener('mousemove', this.mousemove); },
mouseup() { this.get('element').removeEventListener('mousemove', this.mousemove); },
mousemove(event) {
var { screenX, screenY } = event;
var { lastX, lastY, lastTime } = this.getProperties('lastX', 'lastY', 'lastTime');
var now = +new Date();
if (Math.abs(screenX - lastX) < DELTA && Math.abs(screenY - lastY)) < DELTA ||
now - lastTime < DELTA_TIME) return;
this.setProperties({ lastX: screenX, lastY: screenY, lastTime: now });
this.handleMouseMove(event);
}
});
如果你想要重复调用你的功能,即使鼠标没有移动,那么是的,你需要一个计时器。为了更好地与Ember运行循环进行互操作,最好使用Ember.run
而不是setTimeout
或setInterval
。 Ember不提供等效的setInterval
,因此您必须反复设置计时器,如
const INTERVAL = 500;
export default Ember.Component.extend({
timer: false,
mousedown(event) { this.startTimer(); },
mouseup(event) { this.stopTimer(); },
startTimer() {
this.set('timer', true);
Ember.run.next(this, this.tick, INTERVAL); },
stopTimer() { this.set('timer', false); },
tick {
// process tick
if (!this.get('timer')) return;
this.startTimer(); // set up timer again
}
});
这需要调整和调试,但我希望你能理解。