2015-05-25 102 views
1

嗨我正要通過carasoul.js代碼和跨越以下幾行代碼就來了:與自定義事件使用isDefaultPrevented()的

if (slideEvent.isDefaultPrevented()) return 

現在isDefaultPrevented()文件給出了foolowing例如:

$("a").click(function(event) { 
    alert(event.isDefaultPrevented()); // false 
    event.preventDefault(); 
    alert(event.isDefaultPrevented()); // true 
}); 

但我沒有附加click event那麼isDefaultPrevented這裏的任何助攻如何? ,整個功能碼可以看到如下::

Carousel.prototype.slide = function (type, next) { 
    var $active = this.$element.find('.item.active') 
    var $next  = next || this.getItemForDirection(type, $active) 
    var isCycling = this.interval 
    var direction = type == 'next' ? 'left' : 'right' 
    var that  = this 

    if ($next.hasClass('active')) return (this.sliding = false) 

    var relatedTarget = $next[0] 
    var slideEvent = $.Event('slide.bs.carousel', { 
     relatedTarget: relatedTarget, 
     direction: direction 
    }) 
    this.$element.trigger(slideEvent) 
    if (slideEvent.isDefaultPrevented()) return 

    this.sliding = true 

    isCycling && this.pause() 

    if (this.$indicators.length) { 
     this.$indicators.find('.active').removeClass('active') 
     var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) 
     $nextIndicator && $nextIndicator.addClass('active') 
    } 

    var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" 
    if ($.support.transition && this.$element.hasClass('slide')) { 
     $next.addClass(type) 
     $next[0].offsetWidth // force reflow 
     $active.addClass(direction) 
     $next.addClass(direction) 
     $active 
     .one('bsTransitionEnd', function() { 
      $next.removeClass([type, direction].join(' ')).addClass('active') 
      $active.removeClass(['active', direction].join(' ')) 
      that.sliding = false 
      setTimeout(function() { 
      that.$element.trigger(slidEvent) 
      }, 0) 
     }) 
     .emulateTransitionEnd(Carousel.TRANSITION_DURATION) 
    } else { 
     $active.removeClass('active') 
     $next.addClass('active') 
     this.sliding = false 
     this.$element.trigger(slidEvent) 
    } 

    isCycling && this.cycle() 

    return this 
    } 

爲什麼用isDefaultPrevented()

回答

1

Bootstrap輪播在有趣的時刻觸發事件,例如在它滑動之前和之後。如果你想要做的事,當這些事件發生時,你可以對此作出反應,像這樣:

$('.carousel').on('slide.bs.carousel', function (e) { 
    // do something before a carousel slides 
}); 

如果你想防止傳送帶從它的默認行爲,你能做到這一點,像這樣:

$('.carousel').on('slide.bs.carousel', function (e) { 
    // prevent the carousel from sliding 
    e.preventDefault(); 
}); 

引導然後檢查如果事件處理函數調用preventDefault()並停止,如果它發生了它的默認行爲:

if (slideEvent.isDefaultPrevented()) return