Gaia/ExistingStylesPatterns

From MozillaWiki
Jump to: navigation, search

Context

Since every reviewer has his/her concerns on every patch, we really need a page to collect existing accepted styles and patterns in the Gaia code base. It's really upset to be rejected just because of the differences between opaque personal opinions of different reviewers.

Please help to contribute to this page to make this more clear and open.

Common Principles

Naming the Anonymous Functions

Anonymous functions should be named, even some reference has already be bound on it:

 var tsEnd = function _tsEnd(evt) {
   // handle the 'transitionend' event here.
 }

Methods belong to components should be named, too. No matter whether it's in JSON or other format:

 init: function ls_init() {
   // initialize the lockscreen
 }
 AppWindow.prototype.focus = function aw_focus() {
   // do focus on the app window
 }

You can notice that these two functions' name has been prefixed with the abbreviation of the component. This is a trick for the lack of namespace in JavaScript.

This would be outdated if the Bug 883377 have been done. This feature make function name can be bound on the reference assign to it:

 var hello = function(){console.log('Hello')};
 // console would know that "assignment" says 'Hello'

This is necessary for ES6's fat arrow function:

 prop = () => {};    // "prop"

Because you can't assign a name to an arrow function as before:

 prop = prop() => {};    // Illegal; syntax error.

Caveats

You should avoid to use the same name between the reference and the function. For example:

 var tsEnd = (function tsEnd(evt) {
   this.element.removeEventListener('transitionend', tsEnd)
 }).bind(this)

This would be failed (not remove the handler) because the statement inside the function, would use the named function as 'tsEnd',not the reference assign to the one generated by the 'bind' function. We can fix this with:

var tsEnd = (function _tsEnd(evt) {
   this.element.removeEventListener('transitionend', tsEnd)
 }).bind(this)

Thus, the 'tsEnd' would be the reference, wherever in the function or out of it.

From Alive

1. All 40+ lines functions would be rejected. It kills reviewer.

2. Don't use constructor to defined all methods. It damage performance and memory efficiency:

http://stackoverflow.com/questions/3493252/javascript-prototype-operator-performance-saves-memory-but-is-it-faster/4041582#4041582