3 ms·
To avoid the whole "what is the `event` variable and where does it come from?" problem they could use element.addEventListener('submit', submit) The second
by harg 4y ago
To avoid the whole "what is the `event` variable and where does it come from?" problem they could use
element.addEventListener('submit', submit)
The second argument to `addEventListener` is a callback that takes the event as its argument. (`element` should be the form and the event should be `submit` for accessibility reasons.)
Also, the author's example comparing `x === window.x` as evidence that it's insufficient to know if the in-scope variable is the same as the one on the window is wrong. The example uses a primitive value (`1`) which in JS are passed by value, so of course whenever you compare 1 with 1 it'll return true regardless of which variable the 1 is stored in. Objects, (that `event`s are an example of) are passed by reference. So you get
const x1 = {foo: 1}
const x2 = {foo: 1}
x1 == x1 // true
x1 == x2 // false
x1 == {foo: 1} // false
So a simple comparison between objects is enough to determine if they are the same instance. But it won't work to see if 2 different objects contain consist of the same property-values as each other.
- eatonphil 4y ago> To avoid the whole "what is the `event` variable and where does it come from?" problem they could use Why avoid something when you can instead learn how it works? :) > Also, the author's example comparing `x === window.x` as evidence that it's insufficient to know if the in-scope variable is the same as the one on the window is wrong. I think you misunderstood it. When you pass an object as an argument to a function it's passed as a reference. It would have been clearer if I used an object (I was trying to simplify the example) but my code is still illustrating what I meant it to even if I substituted `window.x = {a:2}` for `window.x = 1`.
- harg 4y agoThe point I was trying to make is that your second example doesn't prove or disprove anything. You're simply comparing a primitive value. 1 will always equal 1, regardless of which variable it's stored in. Your first example is enough to conclude that the locally scoped `event` is the same as the one on the window object, due to the pass-by-reference nature of JS objects. The fact that comparing the two returns true means they must be the same object.
- eatonphil 4y agoYes! But you're still missing the point. There is a big difference because it's a matter of which api you're using. window.event may be a deprecated api but the thing that sends the event to the string event handler isn't. It doesn't matter that they're the same object it's about apis.