简体   繁体   中英

what is different between custom event by colon vs dot

i try JavaScript and jQuery (i know jQuery is old but it is just for learning), i create a tools and i need activate some functions by triggered events, this is easy but the problem is custom event names and i don't know what is different between this 4 lines:

1: test.run

2: test:run

3: run.test

4: run:test

question A: they are same?

question B: what is different?

question C: which one is better to used?

question D: if i trigger "run" without "test" which one is triggered?

(for example name space is "test" and event name is "run")

A: They are not the same.

B: The difference is in the syntax and the meaning.

  1. "test.run" is a property or method access on the "test" object, and it's not a valid event name
  2. "test:run" is not a standard syntax for event names in JavaScript or jQuery, it might work in some cases but it's not recommended
  3. "run.test" is also not a standard syntax for event names and it's not recommended
  4. "run:test" is also not a standard syntax for event names and it's not recommended C: The recommended syntax for custom event names in JavaScript and jQuery is "eventName" or "namespace.eventName", for example "run" or "test.run". The latter allows you to group related events under a specific namespace, making it easier to manage and remove them.

D: If you trigger "run" without "test" none of the above mentioned events will be triggered.

It's worth noting that you should use event names that are specific to your application and that make sense to you and other developers. It's also a good practice to use namespaces when you have multiple events that are related to each other in some way, to avoid conflicts and make it easier to manage the events.

A: They are not the same.

B: "test:run" has no special meaning. According to the docs :

You can use any name for a custom event, however you should beware of creating new events with names that might be used by future DOM events. For this reason, in this article we have chosen to use light: for all of our event names, as events with colons are unlikely to be used by a future DOM spec.

"test.run" , on the other hand, consists of jQuery's concept of namespaces, which are not present in native JS events. It comes under the root event "test" , so if you fire the event "test" , anything under the namespace "test" will be fired as well, including "test.run" or "test.run.somethingelse" . If you fire the event "test.run" , however, only "test.run" will be fired, as well as its sub-events.

C: There's not necessarily a better one, just one is used for special purposes, ie namespaces.

D: Apparently spaces is another way to write namespaces instead of using dots.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM