2016-09-21 3 views
0

Я пытаюсь сделать как очередь оповещения о выбросах. До сих пор я достиг этого. Проблема возникает, когда я пытаюсь реализовать прерывания. Предположим, что одностороннее событие запускает одно предупреждение, и до его окончания тайм-аут запускается онлайн-событие. Я хочу, чтобы он убивал офлайн-предупреждение и вместо этого показывал онлайн-предупреждение. Дело в том, что таймаут не работает, как я ожидаю, в этом случае.setTimeout и clearTimeout Прерывание

Вот Угловой сервис, который обрабатывает предупреждение:

.factory('AlertDrop', ['$rootScope', '$q', function ($rootScope, $q) { 
     var timeout = 2000; 
     $rootScope.DropAlerts = []; 
     var hideonclick = false; 
     var listenerOn = false; 
     var t = this; 
     this.currentAlert = {}; 

     var getColor = function (clase) { 
      switch (clase) { 
       case 'error': 
        return 'rgba(201,48,44,0.9)'; 
        break; 
       case 'warning': 
        return 'rgba(240,173,78,0.9)' 
        break; 
       case 'success': 
        return 'rgba(68,157,68,0.9)' 
        break; 
       case 'info': 
        return 'rgba(49, 176, 213,0.9)' 
        break; 
       default: 
        console.log('Código de color incorrecto. Cargo color por defecto.'); 
        return 'rgba(152,26,77,0.9)'; 
        break; 
      } 
     }; 

     this.requestTypes = [ 
      { 
       type: 'offline', 
       class: 'error' 
      }, 
      { 
       type: 'online', 
       class: 'success' 
      } 
     ]; 

     this.bgcolor = 'rgba(201,48,44,0.9)'; 

     this.showAlert = function (params) { 
      this.currentAlert = params; 
      delete t.ctout; 
      t.ctout = {}; 
      var deferred = $q.defer(); 


      if (params.timeout) { 
       this.timeout = params.timeout 
      } 

      if (params.hideonclick) { 
       hideonclick = params.hideonclick; 
      } 

      if (params.class != '') 
       this.bgcolor = getColor(params.class); 

      if (params.class != '') { 
       $('.alertDrop').attr('style', 'background: ' + this.bgcolor + '; top:44px;'); 
      } else { 
       $('.alertDrop').attr('style', 'top:44px;'); 
      } 

      if (hideonclick) { 
       addListener(this.bgcolor); 
      } 

      $('.alertDrop').html(params.message); 

      t.ctout = setTimeout(function() { 
       timeoutDone(); 
      }, this.timeout); 
     }; 

     this.hideAlert = function (color) { 
      $('.alertDrop').css('top', '0'); 
      rmListener(); 
     }; 

     var rmListener = function() { 
      if (listenerOn) { 
       $('.alertDrop').unbind('click'); 
      } 
     }; 

     var addListener = function (color) { 
      if (!listenerOn) { 
       // $('.alertDrop').on('click', t.hideAlert(color)); 
      } 
     }; 

     var timeoutDone = function(){ 
      var deferred = $q.defer(); 
      t.hideAlert(this.bgcolor); 
      var tt = setTimeout(function(){ 
       t.changeStatus(false); 
       deferred.resolve(true); 
      },2000); // 2 segundos, tiempo establecido en style.css 
      return deferred.promise; 
     }; 

     var removeOnlines = function(){ 
      $rootScope.DropAlerts = $rootScope.DropAlerts.filter(function(el){ 
       return el.type != 'online'; 
      }); 
     }; 

     var removeOfflines = function(){ 
      $rootScope.DropAlerts = $rootScope.DropAlerts.filter(function(el){ 
       return el.type != 'offline' 
      }); 
     }; 

     var interrupcion = function(params){ 
      var load = true; 
      if(params.type == 'offline'){ 
       removeOnlines(params); 
       load = false; 
      }else if(params.type == 'online'){ 
       removeOfflines(params); 
       load = false; 
      } 
      if(load){ 
       $rootScope.DropAlerts.push(params); 
      }else{ 
       clearTimeout(t.ctout); 
       timeoutDone().then(function(){ 
        t.showAlert(params); 
       }); 
      } 
     }; 

     this.checkPush = function(params){ 
      var deferred = $q.defer(); 
      if($rootScope.AlertDropActive){ 
       if(params.type == this.currentAlert.type){ 
        clearTimeout(this.ctout); 
        setTimeout(function(){ 
         timeoutDone(); 
        },this.timeout) 
       }else{ 
        interrupcion(params); 
       } 
       deferred.resolve(true); 
      }else{ 
       $rootScope.DropAlerts.push(params); 
       deferred.resolve(true); 
      } 
      return deferred.promise; 
     }; 

     this.pushAlert = function (params) { 
      this.checkPush(params); 
      if (!$rootScope.AlertDropActive) { 
       this.changeStatus(true); 
       var alert = $rootScope.DropAlerts.shift(); 
       this.showAlert(alert); 
      } 
     }; 

     this.changeStatus = function(v){ 
      $rootScope.AlertDropActive = v; 

      if (!$rootScope.AlertDropActive && ($rootScope.DropAlerts.length > 0)) { 
       this.changeStatus(true); 
       var alert = $rootScope.DropAlerts.shift(); 
       this.showAlert(alert); 
      } 
     }; 

     return { 
      showAlert: this.showAlert, 
      hideAlert: this.hideAlert, 
      pushAlert: this.pushAlert, 
      changeStatus: this.changeStatus, 
      currentAlert: this.currentAlert, 
      checkPush: this.checkPush 
     }; 
    }]); 

Так что, когда я огнь функции interrupcion, только в том случае, когда соединение будет восстановлено или потерянными, мне нужно, чтобы остановить текущий тайм-аут и после того, как предупреждение скрыто, показать новое событие.

Я показываю это на div с переходом 2 секунды.

Любые идеи?

ответ

0

Фактически ошибка была не в коде, который я отправил, но когда я вызвал pushAlert. Я добавил таймаут, чтобы попытаться смоделировать быстрые изменения событий, и это было бесполезно с таймаутами.

Смежные вопросы