我使用Backbone和require.js以及jQuery。 我想要做的是簡單地將一個事件綁定到應該顯示(鼠標懸停)或隱藏(鼠標懸停)視頻的容器。事件發生,但不幸的是太多次(我有.intro-content
內的幾個孩子)。我嘗試使用ev.stopPropagation()
(如代碼所示)和ev.stopImmediatePropagation
,但這並不能防止冒泡。我究竟做錯了什麼?多次發射骨幹事件
查看:
define([
'jquery',
'underscore',
'backbone',
'global'
], function($, _, Backbone, Global){
var VideoView = Backbone.View.extend({
el: $('#splitlayout'),
events: {
'mouseover .side-left .intro-content': 'checkVideoState',
'mouseout .side-left .intro-content': 'checkVideoState'
},
render: function(){
this.playVideo('video', '0GsrOOV0gQM');
this.delegateEvents();
},
initialize: function() {
_.bindAll(this);
this.render();
},
checkVideoState: function(ev) {
ev.stopPropagation();
if(!$('#video').hasClass('active') && ev.type == 'mouseover') {
this.showVideo();
} else if($('#video').hasClass('active') && ev.type == 'mouseout') {
this.hideVideo();
}
},
showVideo: function() {
console.log('test');
$('#video').addClass('active');
player.playVideo();
},
hideVideo: function() {
console.log('test');
$('#video').removeClass('active');
player.pauseVideo();
},
playVideo: function(container, videoId) {
var self = this;
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
window.onYouTubeIframeAPIReady = function() {
self.loadPlayer(container, videoId);
};
$.getScript('//www.youtube.com/iframe_api');
} else {
self.loadPlayer(container, videoId);
}
},
loadPlayer: function(container, videoId) {
player = new YT.Player(container, {
videoId: videoId,
playerVars: {
controls: 0,
loop: 1,
modestbranding: 0,
rel: 0,
showinfo: 0
},
events: {
'onReady': this.onPlayerReady
}
});
},
onPlayerReady: function() {
player.setPlaybackQuality('hd720');
player.seekTo(8,false);
player.pauseVideo();
}
});
return VideoView;
});
謝謝你的答案,但和的mouseenter做鼠標離開也激發的事件多次.. – enyce12
@ enyce12請確保你沒初始化你的視圖兩次這裏是一個雙重事件的例子http://jsfiddle.net/rph4R/你可以通過刪除最後一行'new VideoView();'來修復它。要檢查這一點,你可以將'console.log('initialize')'添加到'initialize'方法並檢查控制檯。 –
@EugeneGlova就是這樣......我在一個路由器和另一個視圖中初始化它。謝謝!你可以在你的答案中加入這個提示嗎? – enyce12