简体   繁体   中英

JavaScript event naming conventions

We just had a discussion wether to use a present or a past form for event names. Fact is, the events get usually trigger after something happened:

store.save(object)
store.trigger("create", object)

I'm wondering if there is any convention for event naming? It would make more sense to use the past form, on the other side I've the impression that using the present form is used more widely.

Are there any good resources on this subject? Are you aware of known JavaScript libraries that use the past form for its events?

I would go with present tense.

Most, if not all, JavaScript frameworks seem to follow the convention set forth by the JavaScript DOM event API; ie to use present tense for event names. When I think about it, this seems most natural to me, despite the fact that events are handled after they are triggered. After all, the event is triggered on event name . Whatever action is performed which is cause to trigger the event, it happens in the current iteration of the event loop. In other words: as far as the event loop is concerned, the event and the action which triggers the event happen simultaneously.

Some frameworks, such as YUI3 , offer an after hook as well as an on hook for custom events. This distinction is put to use in YUI's attribute library (amonst others):

Listeners registered using the on method, are notified before the stored state of the attribute has been updated. [...]

Since these listeners are invoked before any state change has occurred, they have the ability to prevent the change in state from occurring [...]

Listeners registered using the after method, are notified after the stored state of the attribute has been updated.

Source: http://yuilibrary.com/yui/docs/attribute/index.html#on-vs-after

I'm not personally aware of any frameworks that use past tense for event names, but then I'm not familiar with all of them.

Bootstrap defines two events for every action. One is triggered upon starting the action and named using the present tense (eg show ). Another is triggered after the action has completed – this one is named with the past participle form ( shown ).

Everything is explained under http://getbootstrap.com/javascript/#js-events

EDIT

I guess this approach makes sense when animations come into play.

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