var TooltipView = Backbone.View.extend({
events : {
'click' : 'onClickOrTouch',
'touchstart' : 'onClickOrTouch'
},
initialize: function() {
this.$target = this.$el.find('span');
this.listenTo(Backbone, 'click', this.onClickOrTouchOutside);
this.listenTo(Backbone, 'touchstart', this.onClickOrTouchOutside);
},
onClickOrTouch: function(e) {
e.originalEvent[this.cid] = true;
this.show();
},
onClickOrTouchOutside: function(e) {
// 自分以外からクリックorタッチされた場合は消す
if (!e.originalEvent[this.cid]) {
this.hide();
}
},
show: function() {
if (!this.isVisible) {
this.$target.addClass('visible');
this.isVisible = true;
}
},
hide: function() {
if (this.isVisible) {
this.$target.removeClass('visible');
this.isVisible = false;
}
}
});
// DOMイベントをBackboneイベントに委譲する
$(document).on('click', function(e) {
Backbone.trigger('click', e);
}).on('touchstart', function(e) {
Backbone.trigger('touchstart', e);
});
$(function() {
new TooltipView({el : $('a.tooltip')});
});
<p><a class="tooltip" href="#">Click me <span>Hi!</span></a></p>
a.tooltip {
position: relative;
display: inline;
}
a.tooltip span {
position: absolute;
width:140px;
color: #FFFFFF;
background: #000000;
height: 30px;
line-height: 30px;
text-align: center;
visibility: hidden;
border-radius: 6px;
}
a.tooltip span:after {
content: '';
position: absolute;
top: 50%;
right: 100%;
margin-top: -8px;
width: 0; height: 0;
border-right: 8px solid #000000;
border-top: 8px solid transparent;
border-bottom: 8px solid transparent;
}
a.tooltip span.visible {
visibility: visible;
opacity: 0.8;
left: 100%;
top: 50%;
margin-top: -15px;
margin-left: 15px;
z-index: 999;
}
External resources loaded into this fiddle: