2

当我使用backbone.js 触发此事件并尝试延迟函数调用时,event.type 从mouseenter 更改为mouseover 控制台日志射出“mouseenter”而第二个日志是“mouseover”为什么转换???

app.newsroomPageElementView = Backbone.View.extend({
 events: {
    'mouseenter .featured-image': 'imageHover',
    'mouseleave .featured-image': 'imageHover'
 },
imageHover: function (e)  {
         Y.log(e.type); // this outputs out mouseenter
        _.delay(function(){ 
         Y.log(e.type); // this outputs mouseover
        }, 500);
    },    
});

是因为 500 毫秒后我的鼠标已经“进入”所以它实际上是鼠标悬停,因为我的鼠标在触发时位于事件上方?

4

1 回答 1

1

This is happening because Backbone is handing you a reference to an object that it then reuses.

As you probably know, the mouseenter event is followed by a mouseover event. You don't have a handler for mouseover, so normally, you wouldn't care.

When a mouseenter event occurs, your handler is called with this object e. This is a reference to some object within Backbone; you log its type, but then you retain a reference to that object in your delay handler.

Then, your event handler returns, and control is given back to the Javascript thread. The mouseover event fires. Your code may ignore it, but Backbone goes ahead and reuses the object it handed you and puts the information about the mouseover event in to it.

Then, your delay expires, and you use e to find out the type of the event... now its got all the mouseover event data in it, so that's what you see.

This should be a salutary lesson to us all. First, be aware that JS deals in object references and, if you store an object that something other than your code has created, and then break the thread, that object can change underneath you. Equally, if you have methods that return arrays or objects, know that your are returning a reference to that array or object... thus, if calling code changes the contents of said array or object, this can mess you up; this is particularly dangerous when you have a private field with a public getter. If you're not careful, you can hand over a reference that allows code to change your objects internals, without you meaning to!

于 2013-02-11T00:00:02.693 回答