方案
我在我的骨干应用中的视图包含多个boxes(which are div elements)
。当用户单击一个框并按住鼠标按钮500毫秒时,我想在左上角显示一个delete
按钮。当用户点击其他任何地方#wrapper
时,该delete
按钮应隐藏。
问题
因此显示delete
按钮不是问题。它确实显示删除按钮,当我点击并按住一秒钟它显示删除按钮半秒然后隐藏。它隐藏是因为我还将click事件添加到其父元素#wrapper
,它实际上隐藏了此删除按钮。
问题
那么当我点击并按住子元素#wrapper
时,如何阻止父元素box
触发点击事件?
这是我的代码
以下是父元素模块的代码
var Boxes = Backbone.View.extend({
el: '#wrapper',
events: {
'click': 'method' //when clicked on wrapper i.e. parent of box trigger method function
},
render: function (PaintBoxModel) {
var paintBoxView = new PaintBoxView({ model: PaintBoxModel });
this.$el.find('#contents').append(paintBoxView.render().el);
return this;
},
method: function () {
console.log('method');
App.Vent.trigger('bodyclicked'); //trigger an event
}
});
这是子元素的模块
var Box = Backbone.View.extend({
events: {
'mousedown': 'mouseHoldDown',
'mouseup': 'removeMouseHoldDown'
},
initialize: function () {
this.timeoutId = 0;
App.Vent.on('bodyclicked', this.removeDeleteBtnShadow.bind(this)); //here I am listening to the click event when parent `#wrapper` is clicked
},
mouseHoldDown: function () {
this.timeoutId = setTimeout(this.addDeleteBtnShadow.bind(this), 500);
},
removeMouseHoldDown: function () {
clearTimeout(this.timeoutId);
},
addDeleteBtnShadow: function () {
this.$el.append('<a href="#" class="remove">X</a>');
this.$el.addClass('is-shadow');
},
removeDeleteBtnShadow: function () {
this.$el.find('.remove').remove();
this.$el.removeClass('is-shadow');
}
});
答案 0 :(得分:2)
将event
作为参数传递并使用.stopPropagation()
。
removeMouseHoldDown: function (e)
{
e.stopPropagation();
}
答案 1 :(得分:0)
我刚刚通过在子函数上添加event.stopPrpagation来解决这个问题。例如 -
var parentView = new Backbone.View.extend({
...
events: {
"click": "renderSomething"
},
renderSomething: function() {
//some rendering code
}
});
var childView = new Backbone.View.extend({
...
events: {
"click": "renderSomething"
},
renderSomething: function(event) {
event.stopPropagation(); //this will stop the event from being propagated to the parent
//some rendering code
}
});