-
Notifications
You must be signed in to change notification settings - Fork 0
/
style_guide.html
719 lines (599 loc) · 37.8 KB
/
style_guide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<!-- plugin styles -->
<link rel="stylesheet" type="text/css" href="stylesheets/highlight-github.css" />
<!-- guides styles -->
<link rel="stylesheet" type="text/css" href="stylesheets/reset.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/main.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/guides.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/overrides.style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/overrides.print.css" media="print" />
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<meta name="generator" content="DocPad v6.79.0" />
</head>
<body class="guide">
<header role="banner">
<div class="container">
<h1 id="logo">
<a href="http://www.sproutcore.com"><img src="images/header/logo.png" alt="SproutCore" /></a>
</h1>
<nav role="navigation">
<ul>
<li><a href="http://sproutcore.com/about/">About</a></li>
<li><a href="http://showcase.sproutcore.com">Showcase</a></li>
<li class="active"><a href="http://guides.sproutcore.com">Guides</a></li>
<li><a href="http://docs.sproutcore.com">Docs</a></li>
<li><a href="http://sproutcore.com/community/">Community</a></li>
<li><a href="http://blog.sproutcore.com">Blog</a></li>
</ul>
</nav>
</div>
</header>
<div id="feature">
<div class="wrapper">
<div class="feature_header">
<a href="/"><img src="images/graphics/guides.png"></a>
<h2><a href="/">SproutCore Guides</a></h2>
<p>These guides are designed to help you write and perfect your code.</p>
</div>
<div class="feature_sidebar">
<a href="index.html" id="guidesMenu">
Guides Index <span id="guidesArrow">▸</span>
</a>
<div id="guides" class="clearfix" style="display: none;">
<a href="index.html" class="guidesMenu">
Guides Index <span class="guidesArrow">▾</span>
</a>
<hr style="clear:both;">
<dl class='L'><dt>Start Here</dt>
<dd><a href='/getting_started.html'>Getting Started: Part 1</a></dd>
<dd><a href='/getting_started_2.html'>Getting Started: Part 2</a></dd>
<dd><a href='/getting_started_3.html'>Getting Started: Part 3</a></dd>
<dd><a href='/core_concepts_sc_object.html'>Classes and SC.Object</a></dd>
<dd><a href='/core_concepts_kvo.html'>Computed Properties, Observers and Bindings</a></dd><dt>Views</dt>
<dd><a href='/views.html'>Core View Concepts</a></dd><dt>Models</dt>
<dd><a href='/records.html'>SproutCore Records</a></dd>
<dd><a href='/fixtures.html'>Using Fixtures</a></dd><dt>Theming</dt>
<dd><a href='/chance.html'>Using Chance, SproutCore's CSS Framework</a></dd>
<dd><a href='/theming_app.html'>Theming Your App</a></dd></dl><dl class='R'><dt>Testing</dt>
<dd><a href='/adding_unit_test.html'>Adding a Unit Test</a></dd>
<dd><a href='/unit_test_framework.html'>Unit Testing</a></dd>
<dd><a href='/writing_unit_tests.html'>Writing Unit Tests</a></dd>
<dd><a href='/running_unit_tests.html'>Running Unit Tests</a></dd>
<dd><a href='/todos_tdd.html'>SproutCore Development Using TDD</a></dd><dt>Extras</dt>
<dd><a href='/build_tools.html'>SproutCore's Build Tools</a></dd>
<dd><a href='/run_loop.html'>The Run Loop</a></dd>
<dd><a href='/enumerables.html'>Enumerables</a></dd><dt>Contributing to SproutCore</dt>
<dd><a href='/style_guide.html'>Javascript Guidelines</a></dd>
<dd><a href='/commit_code.html'>Committer Guidelines</a></dd>
<dd><a href='/documentation_guidelines.html'>Documentation Guidelines</a></dd>
<dd><a href='/contribute.html'>Contributing Guides</a></dd><dt>Thanks</dt>
<dd><a href='/credits.html'>Credits</a></dd></dl>
</div>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='headerSection'>
<h2>Javascript Guidelines</h2>
<p>Coding and naming convention style guidelines make your code clearer, easier to read and, they can also actually improve performance.<br /><br />Although you can use any convention that makes sense for you, the guidelines described here are based on years of experience from SproutCore developers in writing understandable and maintainable code.<br /><br />The SproutCore coding and naming convention style guidelines are based on the Cocoa style guide from <a href='http://cocoadevcentral.com/'>CocoaDevCentral</a>.</p>
</div>
<h3 id='-Classes-'>1 - Classes
</h3>
<p>Although JavaScript is a prototype-based language, SproutCore overlays the some
of the concepts of traditional class-based programming for ease of use.</p>
<h4 id='-Defining-Classes-'>1.1 - Defining Classes
</h4>
<p>Just as with Objective-C, JavaScript and thus, SproutCore, is not natively name
spaced. Therefore, it is very important to be careful to use a consistent
prefix when naming your classes. When you create a SproutCore application using
the build tools, it will automatically set up a name space variable for you in
core.js in your project.</p>
<p>For example, if you are writing an application called "AddressBook", the build
tools will create the following:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs undefined"><span class='comment'><div class='filename'>"apps/address_book/core.js"</div></span>
AddressBook = SC.Application.create({
// ...
});</code></div></pre>
<p>In SproutCore, class names are always capitalized. If you are extending an
existing SproutCore view, it is generally preferred to add the name of the view
to the end of the class name. For instance, if you extend a <tt>CollectionView</tt> in
your AddressBook application to show a list of Contact objects, you would do it
in the following manner:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">AddressBook.ContactCollectionView = SC.CollectionView.extend({
<span class="hljs-comment">// Add your custom properties and functions here.</span>
});</code></div></pre>
<h4 id='-Instantiated-Classes-'>1.2 - Instantiated Classes
</h4>
<p>If you are creating an instantiated SproutCore class, such as a controller, the
naming convention is slightly different. An instantiated class is named using
camel case with the first letter lowercase. If you're creating an
<tt>ArrayController</tt> to control your <tt>Contact</tt> objects, you would do the
following:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">AddressBook.contactsController = SC.ArrayController.create({
<span class="hljs-comment">// Add your custom properties and functions here.</span>
});</code></div></pre>
<h4 id='-Create-vs-Extend-and-Design-'>1.3 - Create vs Extend and Design
</h4>
<p>You may have noticed that the first two examples use <tt>.create()</tt> and the third
uses <tt>.extend()</tt>. When should you use one of the other?</p>
<p>When you use <tt>.create()</tt>, you are creating an instance of a class. It is
similar to using the new operator. On the other hand, when you use <tt>.extend()</tt>,
the resulting object is created as a new a subclass, where the properties and
functions from the base class are added in addition to the things that you
define on your own.</p>
<p><tt>.design()</tt> is essentially the same as <tt>.extend()</tt>. It allows Greenhouse and
the SproutCore design framework to create parallel classes that can be used to
manipulate views at design time. Unless you're including the design
framework, <tt>.design()</tt> works the same as <tt>.extend()</tt>.</p>
<h3 id='-Properties-and-Variables-'>2 - Properties and Variables
</h3>
<p>Descriptive property and variable names are strongly encouraged in SproutCore.
Since most deployed applications will deliver the JavaScript compressed to the
user, using terse names will not significantly reduce the amount sent over the
wire. Also, if any obfuscation is used as part of the build process, it will
optimize the names for you. Therefore, naming your variables or properties as
descriptive as you need will make the life of the developer a lot better and
not degrade performance or the user experience.</p>
<p>All properties and variable names are camel case with the first letter lower
case. The name should describe what the variable or property contains. It is
not necessary to indicate the type of a variable in the name. For example, you
don't need to name a variable meant to store a string <tt>myString</tt> or an array
variable <tt>myArray</tt>, but it is useful to name them in such a way that it is
obvious anyway.</p>
<p>The only exceptions are <em>booleans</em>. When naming a boolean, it is recommended
that you prefix them with <tt>is</tt> or <tt>isNot</tt>. Therefore, it is easy to determine
in which manner they are to be used.</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">isEnabled: <span class="hljs-literal">true</span>, <span class="hljs-comment">// This is good.</span>
enabled: <span class="hljs-literal">true</span> <span class="hljs-comment">// This is possibly confusing.</span></code></div></pre>
<h4 id='-Properties-'>2.1 - Properties
</h4>
<p>A property is a variable that is directly defined on an object or class. These
properties can be either public or private. Since JavaScript has no actual
concept of private properties, the concept is merely to help developers. A
private property name is prefixed with a underscore. In the following example
of the <tt>contactController</tt>, there are two properties, first there is property
called <tt>contactsList</tt> that is a public array containing the list of contacts,
and then there is a private property called <tt>_contactsCount</tt> for internal book
keeping. No matter if the property is static or if it is a computed property
(which is actually a function), the naming convention is the same.</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">AddressBook.contactsController = SC.ArrayController.create({
<span class="hljs-attr">_contactsCount</span>: <span class="hljs-number">0</span>, <span class="hljs-comment">// This is a private variable.</span>
<span class="hljs-comment">// This is a public variable. Access using get() and set()</span>
contactsList: []
});</code></div></pre>
<div class='note'><p> To access or modify public properties inside or outside the object,
*always* use the get and set functions on the object, i.e.:
<tt>this.get('contacts')</tt>. For private properties, always access them directly
(i.e., <tt>this._contactsCount = 23;</tt>) If you find yourself accessing private
variables from other objects, make them public and use get and set to access
them. You can also use the getPath and setPath functions if you need to
access/set a deeper property. This is not as fast, but it can make your code
more readable.
</p></div>
<h4 id='-Variables-'>2.2 - Variables
</h4>
<p>Variables are internal to a function only. Since it is local to that function,
it is not encouraged to use an underscore as a prefix.</p>
<p>JavaScript will allow you to reference any variable name, even if you have not
declared it before. If you reference a variable without declaring it first,
however, the variable will be treated as a "global" variable, accessible to
every function in your application. Since SproutCore applications are often
very complex, it is important that you always use the <tt>var</tt> statement to
declare your local variables first. Otherwise you may introduce bugs
inadvertently. Mistakenly defining something outside of its scope is a typical
error that can be very difficult to debug.</p>
<p>In addition, local variables are the fastest way of storing data in JavaScript.
Making extensive use of local variables will get the best performance out of
your code.</p>
<p>For example, in this function, <tt>count</tt> is a local variable:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">countContacts: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-keyword">var</span> count = <span class="hljs-number">0</span>; <span class="hljs-comment">// This is local.</span>
}</code></div></pre>
<p>However, in this function, <tt>count</tt> is not a local variable, but rather a global
variable defined in the window scope:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">countContacts: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
count = <span class="hljs-number">0</span>; <span class="hljs-comment">// This is NOT local, and VERY BAD.</span>
}</code></div></pre>
<h5 id='-Optimizing-the-use-of-variables-'>2.2.1 - Optimizing the use of variables
</h5>
<p>When you access a property defined on an object multiple times, it is
encouraged to store it locally inside the function. For instance, if you have a
function that gets content of a view, collects some information from the record
and then returns a string with all of the values combined. The first example
is not efficient because there are many unnecessary function calls. Not only
that, it is also hard to read! The second example pulls the content object into
a local variable, <tt>contact</tt> and constructs the string with far fewer function
calls and with far superior readability to boot.</p>
<p>This is confusing and inefficient:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">constructName: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-keyword">return</span> [<span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>).get(<span class="hljs-string">'prefix'</span>),
<span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>).get(<span class="hljs-string">'firstName'</span>),
<span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>).get(<span class="hljs-string">'middleName'</span>),
<span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>).get(<span class="hljs-string">'lastName'</span>),
<span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>).get(<span class="hljs-string">'suffix'</span>)].join(<span class="hljs-string">' '</span>);
}</code></div></pre>
<p>This is more readable and far faster since the commonly accessed property is
saved locally:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">constructName: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-keyword">var</span> contact = <span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>);
<span class="hljs-comment">// This is more readable and far faster.</span>
<span class="hljs-keyword">return</span> [contact.get(<span class="hljs-string">'prefix'</span>),
contact.get(<span class="hljs-string">'firstName'</span>),
contact.get(<span class="hljs-string">'middleName'</span>),
contact.get(<span class="hljs-string">'lastName'</span>),
contact.get(<span class="hljs-string">'suffix'</span>)].join(<span class="hljs-string">' '</span>);
}</code></div></pre>
<p>This is best (using the <tt>getEach</tt> function):</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">constructName: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-comment">// This is EVEN more readable.</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.get(<span class="hljs-string">'content'</span>)
.getEach(<span class="hljs-string">'prefix'</span>,<span class="hljs-string">'firstName'</span>,<span class="hljs-string">'middleName'</span>,
<span class="hljs-string">'lastName'</span>,<span class="hljs-string">'suffix'</span>)
.join(<span class="hljs-string">' '</span>);
}</code></div></pre>
<p>Another strategy that often works well is to declare all of your local
variables at the beginning of your method. The YUI compressor recommends
declaring all variables on one line, like:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"> <span class="hljs-keyword">var</span> a, b, x, obj;</code></div></pre>
<h3 id='-Functions-'>3 - Functions
</h3>
<p>This is perhaps where the naming and coding style guidelines for SproutCore
deviate the most from Objective-C. The reason is that the syntactic sugar is
very different between Objective-C and JavaScript.</p>
<p>For SproutCore applications, the naming conventions are more or less the same
as those used to name properties. Just as with properties, private functions on
objects are prefixed with an underscore. The name of a function should be
descriptive and give a sense of what purpose it is intended to perform.</p>
<p>This, however, is not a blank check to make a function name a full sentence.
Naming a function <tt>constructContactFullNameWithPrefixAndSuffixString</tt> is not
helping anyone, especially you, the developer. The specifics can be captured in
the documentation. Instead, naming the function <tt>constructName</tt> gives a hint at
what the function does and is not exceedingly verbose.</p>
<h4 id='-Observers-'>3.1 - Observers
</h4>
<p>If you are creating a function that serves as an observer, it is not required,
but strongly encouraged to add the <tt>DidChange</tt> suffix to the name. Also, if the
observer function is only observing one property, it is nice to name it after
the name of the observed property. Below is an observer function observing
the <tt>isSelected</tt> boolean property of a view:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">isSelectedDidChange: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-comment">// Do stuff based on selection.</span>
}.observes(<span class="hljs-string">'isSelected'</span>)</code></div></pre>
<p>If you are observing more than one property, it is not useful to name the
function after all the properties. In this case, naming the observer function
after the first observed property is acceptable but it is also okay to name it
something descriptive that hints at what happens in the function when it is
triggered. For example, if you are observing multiple properties, such
as <tt>content</tt>, <tt>isSelected</tt>, and <tt>dimensions</tt> and when any of those change, a
redraw of your view will be triggered, you can name it as such:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">redrawStateDidChange: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-keyword">this</span>.displayDidChange(); <span class="hljs-comment">// Redraw the view.</span>
}.observes(<span class="hljs-string">'content'</span>, <span class="hljs-string">'isSelected'</span>, <span class="hljs-string">'dimensions'</span>)</code></div></pre>
<h4 id='-Bindings-'>3.2 - Bindings
</h4>
<p>Bindings are special properties that will connect together the values of two
objects in your application. Unlike most parts of SproutCore, you must follow
a very specific formula for bindings to work properly. To bind to the value
property of one object from the <tt>title</tt> object of another property, you must
add a property to the object you are binding TO that looks like this:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"> valueBinding: <span class="hljs-string">"MyApp.anotherObject.title"</span></code></div></pre>
<h3 id='-Constants-'>4 - Constants
</h3>
<p>A constant is a value that will not change throughout your application.
Constant values can make your code both easier to read and help it to perform
better. Instead of using the same string or number to represent some state,
define constants on your application or classes instead.</p>
<p>Constants should always be named using all upper case, separating words with
underscores. You should always define constants in your application namespace
or on a class. Never define a global constant that is not prefixed by a
namespace as it may conflict with other libraries you load.</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript">MyApp.DEFAULT_CONTACT_COUNT = <span class="hljs-number">23</span>; <span class="hljs-comment">// Good - defined on app namespace</span>
MyApp.controller.HELP_LINK = <span class="hljs-string">"/help"</span>; <span class="hljs-comment">// Good - defined on a class</span>
CONTACT_FIELDS = [<span class="hljs-string">'firstName'</span>, <span class="hljs-string">'lastName'</span>]; <span class="hljs-comment">// Bad - no globals!</span></code></div></pre>
<h3 id='-Other-Coding-Style-Guidelines-'>5 - Other Coding Style Guidelines
</h3>
<p>SproutCore does not have a lot of specific coding style guidelines but the ones
that it does have help a SproutCore application to be readable, maintainable,
and easily extended.</p>
<h4 id='-Two-Space-Soft-tabs--'>5.1 - Two Space Soft tabs!
</h4>
<p>One very important, yet easy way to ensure that your code is readable is to
have a consistent code indent scheme. SproutCore's standard is to have a two
space soft tab instead of an actual tab. This makes the code much more readable
and it is easy to set up your favorite text editor to do this.</p>
<h4 id='-Value-vs-Content-'>5.2 - Value vs Content
</h4>
<p>Usually a property named value represents a simple JavaScript value of an
object, such as a string, a number, etc. A property named <tt>content</tt> (or ending
in <tt>Content</tt>) represents an Object that you will show one or more aspects of.
For example, if you set the <tt>value</tt> property on an <tt>SC.LabelView</tt> to a string,
the label view will show that string directly. If you set the <tt>content</tt>
property on the <tt>SC.LabelView</tt> to a <tt>Contact</tt> object and then set the
<tt>contentValueKey</tt> to <tt>fullName</tt>, then the <tt>SC.LabelView</tt> will show the value of
the <tt>fullName</tt> property on the <tt>content</tt> object.</p>
<h4 id='-Always-Use-Curly-Brackets-for-If-statements-'>5.3 - Always Use Curly Brackets for If statements
</h4>
<p>It is OK to use the curly brackets after a <tt>while</tt>, <tt>for</tt>, or <tt>if</tt> statement
but ONLY if the following bit does NOT fit on the same line. Never, ever,
separate <tt>while</tt>, <tt>for</tt>, or <tt>if</tt> statements from their predicated onto separate
lines without wrapping in curly braces. This creates lots of programming
errors:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"><span class="hljs-keyword">if</span> (isReady) readyCount++; <span class="hljs-comment">// OK - one line</span>
<span class="hljs-keyword">if</span> (isReady)
readyCount = oldReadCount + newReadyCount; <span class="hljs-comment">// not OK!</span>
<span class="hljs-keyword">if</span> (isReady) {
readyCount = oldReadyCount + newReadyCount ;
} <span class="hljs-comment">// OK - multi-line but wrapped in curly-Qs.</span></code></div></pre>
<h3 id='-Performance-'>6 - Performance
</h3>
<p>While some style guidelines just make for more readable code, the suggestions
in this section will actually make your code faster. Ignore them at your own
peril.</p>
<h4 id='-Always-use-----'>6.1 - Always use ===
</h4>
<p>You should always use <em>===</em> and <em>!==</em> when comparing objects. This special
form of equality is both faster and performs fewer transforms on the values you
are comparing. It will behave more like you would expect compare to other
languages than <em>==</em> or <em>!=</em>. If you want to see if a value is either <tt>null</tt>
<strong>OR</strong> <tt>undefined</tt>, use <tt>SC.none(foo)</tt>.</p>
<h4 id='-Cache-Length-in-For-Loops-'>6.2 - Cache Length in For Loops
</h4>
<p>When writing <tt>for()</tt> loops, first capture the length you want to iterate
through like so:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"><span class="hljs-keyword">var</span> idx;
<span class="hljs-keyword">for</span>(idx = <span class="hljs-number">0</span>, len = items.length; idx < len; idx++) {
item = items[idx]; <span class="hljs-comment">//do stuff...</span>
}</code></div></pre>
<p>Better yet, if the order you iterate does not matter, use a <tt>while</tt> loop like
below since it is faster than using a for loop:</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"><span class="hljs-keyword">var</span> idx = items.length;
<span class="hljs-keyword">while</span>(--idx) {
<span class="hljs-comment">//do stuff</span>
}</code></div></pre>
<h4 id='-Avoid-Creating-Closures-'>6.3 - Avoid Creating Closures
</h4>
<p>Closures functions are a convenient way to define iterators and callbacks but
they come at a price. When you define a closure function, the function will
have to be recreated every time the surrounding function is called. In
addition, closures can capture and hold your application's stack state for a
long time, possibly leading to memory leaks, especially in IE.</p>
<p>Instead of using iterators like <tt>forEach()</tt> that require a closure, use
simple <tt>for()</tt> or <tt>while()</tt> loops instead. If you do need to provide a
function for a callback, define the function as a method on your object and
pass a pointer to the method instead. All SproutCore classes that accept
callback functions (such as <tt>addObserver()</tt>, <tt>removeObserver()</tt>,
and <tt>invokeLater()</tt>) all accept both a target object and a method so you can
avoid creating closures in most cases.</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"><span class="hljs-comment">// Bad - this function creates a closure function</span>
<span class="hljs-comment">// to iterate over the array, AND creates a closure</span>
<span class="hljs-comment">// function to pass as a callback to addObserver().</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// (This method also recreates the 'keys' array each</span>
<span class="hljs-comment">// time it is called)</span>
setupObservers: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">var</span> keys = [<span class="hljs-string">'firstName'</span>, <span class="hljs-string">'lastName'</span>];
keys.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">key</span>) </span>{
<span class="hljs-keyword">this</span>.addObserver(key, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'%@ did change!'</span>.fmt(key)) ;
});
});
}
<span class="hljs-comment">// Good - this function uses a simple for loop, passes a</span>
<span class="hljs-comment">// target and method as the callback.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// (It also defines the keys array as a constant that is</span>
<span class="hljs-comment">// not recreated each time.)</span>
OBSERVER_KEYS: [<span class="hljs-string">'firstName'</span>, <span class="hljs-string">'lastName'</span>],
<span class="hljs-attr">keyDidChange</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">target, key</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'%@ did change!'</span>.fmt(key));
},
<span class="hljs-attr">setupObservers</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">var</span> keys = <span class="hljs-keyword">this</span>.OBSERVER_KEYS, len = keys.length, idx;
<span class="hljs-keyword">for</span>(idx=<span class="hljs-number">0</span>;idx<len;idx++) {
<span class="hljs-keyword">this</span>.addObserver(keys[idx], <span class="hljs-keyword">this</span>, <span class="hljs-keyword">this</span>.keyDidChange);
}
}</code></div></pre>
<h4 id='-Beware-of-Redefining-Arrays-'>6.4 - Beware of Redefining Arrays
</h4>
<p>Arrays are first class objects in JavaScript. This means every time you define
an empty array, you are actually creating an object. When you write code,
think about those times when you define new arrays and try to keep them to a
minimum, especially in loops or other "hot" code. Instead of defining a new
array, consider reusing an existing array and just resetting its length to 0.</p>
<pre class="highlighted"><div class="code_container"><code class="hljs javascript"><span class="hljs-comment">// Good - reuses the array to collect temporary values</span>
enqueItems: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">var</span> items = <span class="hljs-keyword">this</span>.get(items), len = items.length, idx;
<span class="hljs-keyword">var</span> cur = [] ; <span class="hljs-comment">// we'll reuse this one</span>
<span class="hljs-keyword">for</span>(idx=<span class="hljs-number">0</span>;idx<len;idx++) {
<span class="hljs-keyword">var</span> item = items[idx];
cur[<span class="hljs-number">0</span>] = item.target ;
cur[<span class="hljs-number">1</span>] = item.method;
<span class="hljs-keyword">this</span>.enqueue(cur);
cur.length = <span class="hljs-number">0</span>; <span class="hljs-comment">// reset array</span>
}
}</code></div></pre>
<p>Also, in these coding examples, you have have noticed that the <tt>{}</tt> are not on
new lines, that is due to the author's stance and not an official guideline.
That is up to the developer to choose how to format your curly-braces since
after it is compressed, it won't really matter!</p>
<h3 id='-Related-Material-'>7 - Related Material
</h3>
<p>Below are links to some additional vidoes that discuss good Javascript
programming practices.</p>
<ul>
<li><a href="http://www.youtube.com/watch?v=mHtdZgou0qU">Google Tech Talk regarding Javascript performance</a></li>
<li><a href="http://www.youtube.com/watch?v=hQVTIJBZook">Javascript: The Good Parts</a></li>
</ul>
<h3 id='-Changelog-'>8 - Changelog
</h3>
<ul>
<li>March 3, 2011: ported by <a href="credits.html#onkis">Mike Ball</a> from the
<a href="http://wiki.sproutcore.com/w/page/12412942/JavaScript-Style-Guide">original wiki entry</a>
written by <a href="credits.html#pbergstr">Peter Bergstrom</a></li>
<li>March 3, 2011: minor adjustments by <a href="credits.html#wagenet">Peter Wagenet</a></li>
<li>August 13, 2013: converted to Markdown format for DocPad guides by <a href="credits.html#topherfangio">Topher Fangio</a></li>
<li>August 13, 2013: many gramatical fixes and minor formatting updates by <a href="credits.html#topherfangio">Topher Fangio</a></li>
</ul>
</div>
<!-- TODO: re-add index_items //-->
<div id="subCol">
<h3 class="chapter"><img src="images/graphics/chapters.png" alt="">Chapters</h3>
<ol class='chapters'>
<li>
<a href='#-Classes-'><p> Classes
</p></a>
<ul>
<li><a href='#-Defining-Classes-'><p> Defining Classes
</p></a></li>
<li><a href='#-Instantiated-Classes-'><p> Instantiated Classes
</p></a></li>
<li><a href='#-Create-vs-Extend-and-Design-'><p> Create vs Extend and Design
</p></a></li>
</ul>
</li>
<li>
<a href='#-Properties-and-Variables-'><p> Properties and Variables
</p></a>
<ul>
<li><a href='#-Properties-'><p> Properties
</p></a></li>
<li><a href='#-Variables-'><p> Variables
</p></a></li>
</ul>
</li>
<li>
<a href='#-Functions-'><p> Functions
</p></a>
<ul>
<li><a href='#-Observers-'><p> Observers
</p></a></li>
<li><a href='#-Bindings-'><p> Bindings
</p></a></li>
</ul>
</li>
<li>
<a href='#-Constants-'><p> Constants
</p></a>
<ul>
</ul>
</li>
<li>
<a href='#-Other-Coding-Style-Guidelines-'><p> Other Coding Style Guidelines
</p></a>
<ul>
<li><a href='#-Two-Space-Soft-tabs--'><p> Two Space Soft tabs!
</p></a></li>
<li><a href='#-Value-vs-Content-'><p> Value vs Content
</p></a></li>
<li><a href='#-Always-Use-Curly-Brackets-for-If-statements-'><p> Always Use Curly Brackets for If statements
</p></a></li>
</ul>
</li>
<li>
<a href='#-Performance-'><p> Performance
</p></a>
<ul>
<li><a href='#-Always-use-----'><p> Always use ===
</p></a></li>
<li><a href='#-Cache-Length-in-For-Loops-'><p> Cache Length in For Loops
</p></a></li>
<li><a href='#-Avoid-Creating-Closures-'><p> Avoid Creating Closures
</p></a></li>
<li><a href='#-Beware-of-Redefining-Arrays-'><p> Beware of Redefining Arrays
</p></a></li>
</ul>
</li>
<li>
<a href='#-Related-Material-'><p> Related Material
</p></a>
<ul>
</ul>
</li>
<li>
<a href='#-Changelog-'><p> Changelog
</p></a>
<ul>
</ul>
</li>
</ol>
</div>
</div>
</div>
<hr class="hide" />
<footer>
<div class="container">
<div class="col">
<a href="index.html"><img src="images/footer/sc_logo_medium.png" alt="SproutCore" /></a>
<p id="license">
SproutCore framework is under MIT License.
</p>
</div>
<nav class="col">
<h1>Site Navigation</h1>
<ul>
<li><a href="http://www.sproutcore.com/about/">About</a></li>
<li><a href="http://docs.sproutcore.com">Docs</a></li>
<li><a href="http://blog.sproutcore.com">Blog</a></li>
<li><a href="http://www.sproutcore.com/install/?redirect=1">Download</a></li>
<li><a href="http://www.sproutcore.com/community/">Community</a></li>
<li><a href="https://github.com/sproutcore/sproutcore">GitHub</a></li>
<li><a href="mailto:community@sproutcore.com">Contact Us</a></li>
<li><a href="http://guides.sproutcore.com">Guides</a></li>
</ul>
<a href="http://www.w3.org/html/logo/"><img src="images/footer/html5_tech.png" alt="HTML5 Powered" /></a>
</nav>
<div class="col">
<h1>Get in Touch, Stay Informed</h1>
<ul class="social">
<li><a href="http://twitter.com/sproutcore"><img src="images/footer/twitter.png" alt="Twitter" /></a></li>
<li><a href="http://www.facebook.com/sproutcore"><img src="images/footer/facebook.png" alt="Facebook" /></a></li>
<li><a href="http://groups.google.com/group/sproutcore"><img src="images/footer/google.png" alt="Google Groups" /></a></li>
<li><a href="http://groups.google.com/group/sproutcore">Subscribe To Mailing List</a></li>
</ul>
<a href="http://eepurl.com/dK1-Y" target="_blank" id="newsletter" class="button secondary">Sign Up For Our Newsletter!</a>
<!-- Commented out until we have mailchimp API integration.
<h2>Subscribe To Newsletter</h2>
<div id="subscribe">
<form>
<input type="text" name="email" />
<button name="subscribe">Sign-Up</button>
<div class="processing"><img src="/img/spinner.gif"></div>
<div class="error"></div>
</form>
</div>
-->
</div>
<a href="#feature" class="top">Back To Top</a>
</div>
</footer>
<script type='text/javascript' src='/javascripts/jquery.min.js'></script>
<script type='text/javascript'>
/*
* Make the guides link clickable
*/
function guideMenu(e){
if (document.getElementById('guides').style.display == "none") {
document.getElementById('guides').style.display = "block";
document.getElementById('guidesArrow').innerHTML = "▾";
$('body').click(function(e){ guideMenu(e); });
} else {
document.getElementById('guides').style.display = "none";
document.getElementById('guidesArrow').innerHTML = "▸";
$('body').unbind('click');
}
return false;
}
$('#guidesMenu, .guidesMenu').click(guideMenu);
</script>
</body>
</html>