为什么有一个“事件"变量可用而没有在上游发生事件时定义? [英] Why is there an 'event' variable available without being defined when there was an event upstream?

查看:19
本文介绍了为什么有一个“事件"变量可用而没有在上游发生事件时定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天偶然发现了一个奇怪的行为.基本上,我有一个绑定到knockout.js 点击事件的函数.该函数利用了淘汰赛事件,但并未明确将其作为参数.

I stumbled across an odd behaviour today. Basically, I had a function bound to a knockout.js click event. The function was making use of the knockout event, but was not explicitly taking it as an argument.

this.myClickHandler = function(){
    console.log(event); //event gets logged in Chrome/IE11, not Firefox
}

这对我来说看起来很奇怪,但在 Chrome 中它按预期工作.它在 IE11 中也能正常工作.但是在 Firefox 中,它不起作用.一旦我明确表示它在所有浏览器中都有效.这是我期望它完全工作所需要的.

This looked weird to me, but in Chrome it was working as expected. It also worked correctly in IE11. In Firefox however, it did not function. As soon as I explicitly it worked in all browsers. This is what I would expect would be needed for it to work at all.

this.myClickHandler = function(model, event){ //event is second parameter passed from knockout click event
    console.log(event); //event gets logged in all browsers
}

我玩了一下,也用 jQuery 复制了这个

I had a play around and reproduced this with jQuery as well

    function func(){
     alert(event);
    }
    
    function runFunc(callback){
      callback();
    }
    
    $(document).ready(function(){
      runFunc(func);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

那么这是如何工作的?为什么我可以在某些浏览器中访问名为event"的变量,而在其他浏览器中却不能访问?这是预期的行为吗?

So how is this working? Why do I have access to a variable called 'event' in some browsers but not others? Is this intended behaviour?

推荐答案

它是从旧版本的 IE 中得到的,在旧版本的 IE 中,事件对象没有传递给处理程序方法,而是在全局上下文中设置.

It is something that got carried from the old version of IE, where the event object was not passed to the handler method instead it was set in the global context.

为了向后兼容,IE 仍然支持这个模型,chrome 也增加了对这个特性的支持.但是FF不支持.

For backward compatibility IE still supports this model and chrome also has added support for this feature. But FF is not supporting it.

这篇关于为什么有一个“事件"变量可用而没有在上游发生事件时定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆