gpt4 book ai didi

javascript - 使用带有定时队列排出的 Ember 观察者

转载 作者:行者123 更新时间:2023-11-28 19:16:00 25 4
gpt4 key购买 nike

我正在尝试为广播覆盖构建某种“通知系统”。本质上,我捕获事件,将它们添加到数组中,然后运行一个观察该数组的函数。每次添加事件时,我都会运行一个需要给定时间的动画,将其从数组中删除,然后移至下一个。

我发现debounce让我达到了目标。我可以在动画运行时添加任意数量的事件,并且可以清空队列。

问题是,我必须等待指定的时间(在本例中为 5 秒)才能处理第一个事件。但是,当我将去抖设置为立即时,一切都会中断,因为第一个事件将立即处理,但其他事件都不会。

# Pool handling.
pool: []

# Function adds events to the pool array.
addEventToPool: (event, data) ->
console.log "added #{event} with #{data} to pool!"
@get('pool').pushObject(data)

# Function that observes the pool array and runs debounce
# if there are any items in the pool.
observePool: (->
Ember.run.debounce(@, @handleEvent, 5000, false) if @get('pool').length
).observes('pool.[]')

# Event handling.
handleEvent: ->
pool = @get('pool')
object = pool.get('firstObject')
@set('payload', object)

Ember.$(".event-message__#{object.event}").addClass('active')

Ember.run.later (->
Ember.$(".event-message__#{object.event}").removeClass('active')
pool.removeObject(object)
), 2000

console.log "Number of remaining objects: #{pool.length}."
console.log "Objects remaining: #{JSON.stringify pool}."

我有一种感觉,我需要放弃 debounce 来解决这个问题,但我不确定该解决方案是什么。

如果您需要任何说明,请告诉我!

最佳答案

Ember.run.debounce

Ember.run.debounce 的目的是,如果在过去 X 秒 内未调用 debounce,则仅运行一次。

它的主要用途是在用户完成输入后启动某种类型的操作 - 因此,对于有人输入的每个字符,您可以调用 Ember.run.debounce(handleInput, 1000)并且您可以确定,无论他们按了多少次键,您的函数都只会运行一次 - 在他们 1 秒没有按任何键之后。

它对于处理滚动事件也很有用 - 比如说在页面上滚动时有数百个滚动事件,但您只想在滚动停止后执行一些操作 - 调用 debounce 数百个times 不会运行它,直到您停止为 timeout 值调用 debounce(例如,在本例中,在最后一个滚动事件后 100 毫秒)。

这似乎与您想要做的有点不同。

建议的解决方案

我认为你想要做的是使用 Ember.run.later。您可以将其全部合并到一个仅观察 pool.firstObject 的函数中 - 因为您总是拉动第一个对象并在完成后将其删除。

handleEvent: Ember.observer('pool.firstObject', function() {
var pool = this.get('pool');
var obj = pool.get('firstObject');
if (obj) {
// add class
Ember.$(".event-message__#{object.event}").addClass('active');

// schedule remove class for 2 seconds from now
Ember.run.later(function() {
Ember.$(".event-message__#{object.event}").removeClass('active');
}, 2000);

// schedule remove object from pool 5 seconds from now
Ember.run.later(function() {
pool.removeObject(obj);
// after you've removed this object (which was firstObject)
// pool.firstObject will change, and the handleEvent function
// will get kicked off again
}, 5000);

}
})

关于javascript - 使用带有定时队列排出的 Ember 观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com