2013-11-24 2 views
0

У меня есть таймер, написанный на javascript. Когда я нажимаю на таймер на моей странице HTML, он приостанавливается. Если я снова нажму на него, он будет продолжать подсчет.Добавьте существующий ClickEvent к кнопке?

Это код таймера:

var Timer = function() {} 
Timer.prototype = { 
    refresh: null, 
    focus: null, 
    sec: 0, 
    min: 0, 
    hour: 0, 
    paused: false, 
    init: function(el) { 
     var that = this; 
     this.el = el; 
     this.clickEvent(); 
     return this; 
    }, 
    set: function(t) { 
     t = t.split(':'); 
     this.hour = t[0]; 
     this.min = t[1]; 
     this.sec = t[2]; 
     return this; 
    }, 
    bindFocus: function() { 
     var that = this; 
     clearInterval(this.focus); 
     if (document.hasFocus) 
      that.focus = setInterval(function() { 
       if (document.hasFocus()) { 
        if (that.paused) { 
         window.clearInterval(this.refresh); 
         that.go(); 
        } 
       } else 
        that.stop(); 
       }, 200); 
    }, 
    clickEvent: function() { 
     var that = this, frag = $('<h2>').addClass('pauseGame').text(texts.pause), toggleFlag = true; 
     this.el.bind('click', timerClicked); 
     function timerClicked(callback) { 
      if (!toggleFlag) 
       return; 
      toggleFlag = false; 
      if (that.paused === false) { 
       that.stop(); 
       window.clearInterval(that.focus); 
       $('#options > button').not('#options > .pause').prop('disabled', true); 
       $('#options > .pause').text('Resume'); 
       board.mainBoard.fadeOut(400, function() { 
        frag.css({ 
         letterSpacing: '25px', 
         opacity: 0 
        }); 
        $(this).after(frag).detach(); 
        frag.parent().addClass('paused'); 
        frag.animate({ 
         opacity: 1 
        }, { 
         queue: false, 
         duration: 400 
        }).animate({ 
         letterSpacing: '-4px' 
        }, 700, "easeOutBack", function() { 
         toggleFlag = true; 
        }); 
       }); 
       that.el.addClass('pause'); 
      } else { 
       $('#options > button').prop('disabled', false); 
       $('#options > .pause').text('Pause'); 
       options.undoToggle(); 
       frag.animate({ 
        opacity: 0, 
        letterSpacing: '25px' 
       }, 600, "easeInBack", function() { 
        $(this).parent().removeClass('paused').end().remove(); 
        board.container.prepend(board.mainBoard).removeAttr('style'); 
        board.mainBoard.fadeIn(400); 
        that.go(); 
        toggleFlag = true; 
       }); 
       this.className = ''; 
      } 
     } 
    }, 
    restart: function(el) { 
     this.sec = this.min = this.hour = 0; 
     this.el.text('00:00'); 
     this.stop().go(); 
    }, 
    go: function(now) { 
     var that = this; 
     this.paused = false; 
     if (now) 
      updateClock(); 
     window.clearInterval(this.refresh); 
     that.refresh = window.setInterval(updateClock, 1000); 
     function updateClock() { 
      that.sec++; 
      if (that.sec == 60) { 
       that.sec = 0; 
       that.min++; 
      } 
      if (that.sec < 10) 
       that.sec = "0" + that.sec; 
      if (that.min == 60) { 
       that.min = 0; 
       that.hour++; 
      } 
      var hours = (that.hour > 0) ? ((that.hour <= 9) ? "0" + that.hour : that.hour) + ":": ''; 
      that.el.html(hours + ((that.min <= 9) ? "0" + that.min : that.min) + ":" + that.sec); 
     } 
     return this; 
    }, 
    stop: function() { 
     this.paused = true; 
     window.clearInterval(this.refresh); 
     return this; 
    } 
}; 

Я также хочу, чтобы приостановить таймер при нажатии на кнопку и возобновить таймер при повторном нажатии на эту кнопку (или таймер). Текущий код кнопки у меня есть в простом HTML:

<div id="options"> 
    <button class="pause" title="pause/resume the game">Pause</button> 
</div> 

Так как это так? Я хочу, чтобы это не имело значения, если вы нажмете кнопку или таймер, оба должны приостановить таймер или возобновить его.

Большое спасибо

ответ

0

Понял: timer.el.trigger('click'); сделал трюк для меня

+0

Не могли бы вы дать нам немного больше контекста, где в вашем примере кода вы сделали это изменение? Как и сейчас, этот ответ на самом деле не говорит нам, как решить проблему, и почему это исправлено. –

+0

Конечно, хотя это была небольшая тропа и ошибка. Эта часть кода таймера запускает/связывает паузу: this.el.bind ('click', timerClicked); Поэтому я использовал это, чтобы имитировать его. Когда я сейчас нажимаю кнопку, он «имитирует» щелчок по таймеру. Замечание Александра указало мне в правильном направлении. – Maurice

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