我使用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