gpt4 book ai didi

javascript - 排队通知的模式?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:44 26 4
gpt4 key购买 nike

我创建了一个库来弹出一些 toast 通知,我试图限制屏幕上的最大通知数。

我设法将想法提取到plunker中(不要介意代码,它只是为了解决问题)。

我有一个函数来创建这些 toast :

function createToast() {
var body = $document.find('body').eq(0);

var toast = {};
toast.id = index++;
toast.el = angular.element('<div class="toast">Toast ' + toast.id + '</div>');
toast.el = $compile(toast.el)($scope);

if (maxOpened && toasts.length >= maxOpened) {
remove(toasts[0].id);
}

toasts.push(toast);
$animate.enter(toast.el, body).then(function() {
$timeout(function() {
remove(toast.id);
}, 3000);
});
}

基本上,它会创建一个带有 el 的新对象,然后将其动画化到 body 上。请注意,如果达到 maxOpened,它会删除第一个。

function remove(id) {
var toast = findToast(id);

if (toast) {
$animate.leave(toast.el).then(function() {
var index = toasts.indexOf(toast);
toasts.splice(index, 1);
});
}

function findToast(toastId) {
for (var i = 0; i < toasts.length; i++) {
if (toasts[i].id === id) {
return toasts[i];
}
}
}
}

找到 toast ,为离开添加动画,然后将其删除。

如果我对它们执行 $interval,假设 600ms 它有效。

在这里试试:http://plnkr.co/edit/lDnT57FPadCt5Ir5wHuK?p=preview

如果将它降低到 100ms 之类的值,它就会开始崩溃,不仅会忽略最大值,还会留下一些不会被删除的孤立 toast。

所以我不确定这里有什么好的解决方案。我最好的猜测是提供一个队列,这样我就可以在 toast 被移除后立即排空它,但到目前为止,我还没有做到。

最佳答案

可能最简单的解决方案是为每个 toast 添加一个延迟,并且仅在未达到或不再达到限制时才开始为 toast 设置动画。

如果尚未达到限制或可以忽略限制,则首先添加延迟并立即解决它:

toast.slotOpen = $q.defer();

toasts.push(toast);
if (maxOpened && toasts.length <= maxOpened || !maxOpened) { // i guess 0 or a falsy value means to ignore the limit
toast.slotOpen.resolve();
}

你只在插槽打开时启动动画:

toast.slotOpen.promise.then(function() {
$animate.enter(toast.el, body).then(function() {

最后要做的是在删除旧 toast 后打开新插槽时解决延迟:

$animate.leave(toast.el).then(function() {
var index = toasts.indexOf(toast);
toasts.splice(index, 1);
if (maxOpened && toasts.length >= maxOpened) {
toasts[maxOpened - 1].slotOpen.resolve();
}

我已经调整了你的代码并创建了一个新的 Plunker .

关于javascript - 排队通知的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862320/

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