继续在ember中调用mouseDown上的函数



我需要继续调用mousedown上的一个函数,我有以下代码:

<button id="zoomin" type="button" {{action "zoomIn" on="mouseDown" target="view" }} class="btn">
    <i class="icon-zoom-in"></i>
</button>

但它只在鼠标放下时被调用,我希望它被反复调用,直到鼠标抬起。

除了timer,还有其他解决方案吗?

我建议使用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而不是setTimeoutsetInterval。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
    }
});

这需要调整和调试,但我希望您能理解。

最新更新