3

设想

我在主干应用程序中的视图由几个boxes(which are div elements). 当用户单击一个框并按住鼠标按钮 500 毫秒时,我想delete在左上角显示一个按钮。当用户点击其他任何地方时#wrapper,该delete按钮应该隐藏。

问题

所以显示delete按钮不是问题。当我单击并按住一秒钟时,它确实显示删除按钮,它显示删除按钮半秒钟然后隐藏。它之所以隐藏,是因为我还将单击事件添加到它的父元素#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');
    }

});
4

2 回答 2

2

event作为参数传递并使用.stopPropagation().

removeMouseHoldDown: function (e) 
{
   e.stopPropagation();
}
于 2013-04-23T07:57:50.423 回答
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
    }
});
于 2013-08-19T13:28:58.013 回答