当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Mouseenter or mouseover prevents click from firing in Backbone/Marionette application

问题描述:

First off, I set up the following Fiddle to show what I'd like to accomplish, using only jQuery:

http://jsfiddle.net/NjmjP/1/

The following three events are bound:

$('.test li p').mouseenter(function() {

var el = $(this),

count = ++mouseenters[el.attr('id')];

el.find('.mouseenters .count').text(count);

});

$('.test li p').mouseover(function() {

var el = $(this),

count = ++mouseovers[el.attr('id')];

el.find('.mouseovers .count').text(count);

});

$('.test li p').click(function() {

function r() {

return Math.floor(Math.random() * 256);

}

$(this).css({'background-color': 'rgb(' + r() + ',' + r() + ',' + r()});

});

Depending on what browser you're using (I'm using Chrome), we see that jQuery is compensating for browser vendors' lack of real support for mouseenter. Mouseover fires whenever the mouse enters or leaves child element, while mouseenter fires only when the mouse enters the DOM element two which the event is bound.

Then I wrote the following in Backbone/Marionette:

http://jsfiddle.net/PhXLf/

Events are bound like this in a Marionette.ItemView:

events: {

'mouseover p' : 'handleMouseOver',

'mouseenter p' : 'handleMouseEnter',

'click p' : 'handleClick'

},

We see here that the mouseenter and mouseover events are both behaving badly (or at least not like the well-behaved jQuery versions) and that click isn't firing at all. I was under the impression that Backbone used jQuery events, but apparently I'm mistaken, or maybe simply saying "Backbone uses jQuery events" doesn't fully address what's happening under the hood.

Suffice to say, I'm very confused about what's going on here. Why are mouseenter/mouseover firing every time the mouse moves in the Backbone version? And why isn't click firing at all? An explanation or workaround would be greatly appreciated.

网友答案:

Updated jsfiddle : http://jsfiddle.net/PhXLf/2/

I believe the events are working the same. In the backbone version you have your entire view being re-rendered every time the model changes. Thus it renders a new div every time the mouse moves, so it registers a new 'mouseenter' event. This also prevents the 'click' event from firing because clicking down triggers a 'mouseenter' after the 'mousedown' and so when you have a 'mouseup' event, it's on a different element from when you clicked down. In the jquery version you are only changing the relevant properties, which is what I would do in this case as well.

    rerender: function() {      
             this.$('.mouseovers .count').html(this.model.get('mouseOverCount'));
             this.$('.mouseenters .count').html(this.model.get('mouseEnterCount'));
    },
分享给朋友:
您可能感兴趣的文章:
随机阅读: