Why is there an 'event' variable available

2019-02-16 00:57发布

问题:

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
}

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
}

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>

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?

回答1:

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.

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

  • Event object references