質問

As I've been reading tutorials on the native drag and drop events, I've come across a conditional that checks for e.preventDefault before calling e.preventDefault(). This conditional is written either as:

e.preventDefault && e.preventDefault();

or

if (e.preventDefault) { 
  e.preventDefault();
}

The tutorials are Native Drag and Drop by Remy Sharp, Drag and Drop and Automatically Send to the Server by Remy Sharp, and Implementing Native Drag and Drop by Matt West.

I've never encountered this pattern before. I'm accustomed to seeing e.preventDefault() called without the conditional. When would e.preventDefault be falsy and is it best practice to use this phrasing in every instance where e.preventDefault is being called?

役に立ちましたか?

解決

It seems like preventDefault behaviour is not standardized across browsers. It explains why jQuery has a wrapper for the native preventDefault() in it's Event object wrapper, making it always present and more predictable. In that case you would not have to do the extra testing for preventDefault and it's value but can just assume it's available where events are. But if you're working without an abstraction library like jQuery, you still have to do the extra testing. jQuery's code for it seems like a good guide.

他のヒント

It will be false if Javascript can't find the function (The browser don't have this function) but anyway it should be "undefined" which will be converted to false. It should be used everytime you call this function if you want to keep compatibility with older browsers.

 e.preventDefault && e.preventDefault ()

If the first condition is true, it will be executed. Anyway, in jQuery you could found an universal way to do it.

Example, if I don't remember wrong, some browsers (IE?) could use e.returnValue to avoid the execution of default action code.

The two codes you added are the same thing and does the same.

When would e.preventDefault be falsy?

It will be undefined in very old browsers that do not respect the DOM specs, such as IE<=8.

Is it best practice to use this phrasing in every instance where e.preventDefault is being called?

No. Listeners that are attached via standard DOM methods also can expect this method to exist. If you care about older browsers, you usually would a framework that shims these anyway.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top