javascripteventsbackbone.jsnaming-conventions

Backbone.js best practice for event handlers naming


Let's say I have a function in a view that triggers when some kind of state is changed. What would be best to name it and why?


Solution

  • I personally prefer to use onEventName names keeping the native naming convention for DOM event handlers.

    Like myElement.onclick = function() { /* ... */ } for click event.

    So for myEvent I'm using a handler named onMyEvent.

    And if I have event stateChange, then I'll use onStateChange handler.

    But really this question is more specific for each team of developers and code-style conventions inside the team/company.

    So the main goal in such kinds of questions is to keep the code style the same in all parts to ensure readability.

    Therefore if you're working in a team, just keep sticky to the team's code writing conventions and if you're working alone on existing code, try to keep its code style (sure if that style is not obviously ugly).

    UPDATE: Understanding.

    What is the event? Roughly it's an action initiated outside or inside the program, in other words, something happens in the system, e.g. some state changes (the state of the keyboard, of the mouse, of I/O devices, etc.) doesn't matter how (the user clicked on mouse or some program sent the mouse click signal to the system).

    Say the browser window is subscribed to get notifications about some events and the operating system sends them to it as soon as possible, we'll assume that at the same time when something happens. So if the user clicks his mouse when the browser window is active and the document has a focus, the browser says to the document to fire the click event. And here our onclick handler starting its invocation. In other words, the system says to us that now happens a change of some state. And we're handling this change and not handling a fact saying to us that the state has been changed.

    Let's assume that our handler is named onClicked. Since the handler's name saying in past tense we can get a reasonable question: "When clicked, how long ago it happened? How many times it was clicked? Hmm, maybe it's too late to handle this action (or actions?) at all...". So this name tells us that something happened sometime in past.

    In contrast when our handler is named onClick it's obvious that click event just fired and fired once and we were notified about it immediately. And we're going to handle the click event - the information saying to us that the state of the mouse changed right now (not mouse clicked, but the event of click).

    So the names in the past tense are more appropriate for the cases when we need to check if some state has been changed or not. E.g. if the variable stores the state = 1 we can call the function isStateChanged(); which will compare the value in state variable with the real value at the current moment. And here the past tense is a good choice for naming.