forked from spine/spine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
886 lines (613 loc) · 43 KB
/
index.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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Spine</title>
<meta name="description" content="Spine is a lightweight MVC framework for building JavaScript applications.">
<meta name="keywords" content="spine,javascript,mvc,framework,backbone,node,web,app">
<link rel="stylesheet" href="site/site.css" type="text/css" charset="utf-8">
<link rel="stylesheet" href="site/highlight.css" type="text/css" charset="utf-8">
<script src="site/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="spine.js" type="text/javascript" charset="utf-8"></script>
<script src="site/highlight.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
hljs.initHighlightingOnLoad();
</script>
</head>
<body>
<div id="container"><h1>Spine</h1>
<p><strong>Spine is a lightweight framework for building JavaScript web applications.</strong> Spine gives you a MVC structure and then gets out of your way, allowing you to concentrate on the fun stuff, building awesome web applications.</p>
<p>Spine is opinionated and, although at first glance it might look similar to other frameworks like Backbone, it actually has quite a different take on things.</p>
<p>Spine is tiny, the library comes in at around 500 lines of JavaScript, that's about 2K minified & compressed. However, it's not about size, it's how you use it, and Spine certainly packs a punch!</p>
<p><strong>Latest version:</strong> <a href="spine.js">0.0.4</a> (<a href="spine.min.js">minified</a>).
Or check out the <a href="http://github.com/maccman/spine">source code</a>.</p>
<h1>Overview</h1>
<p>So, what's so special about Spine, how does it stand out from the crowd?</p>
<ul>
<li>Class library with <strong>real</strong> prototypal inheritance</li>
<li>Lightweight <strong>controller</strong> implementation, based on Backbone's API</li>
<li>Full <strong>model</strong> layer and ORM</li>
<li>Ajax and HTML5 Local Storage adapters baked in</li>
<li>Asynchronous server communication</li>
<li>Works in <strong>all major browsers</strong> (Chrome, Safari, Firefox, IE >= 7)</li>
<li>Simple and lightweight</li>
<li>Thorough documentation</li>
</ul>
<p>But don't take my word for it. Take a look at the source of the example applications below, and decide for yourself.</p>
<h1>Tutorials</h1>
<p>Spine has a growing <strong><a href="http://maccman.github.com/spine.tutorials/">set of tutorials</a></strong>, from layouts, tabs and sidebars to forms, updating records and validation.</p>
<h1>Examples</h1>
<p>Spine includes some great example applications to show you what's possible with the framework, and give you a practical understanding of the library. Although Spine is cross browser, it's worth noting that some of the examples are for WebKit based browsers only (Chrome/Safari), due to browser specific CSS (i.e. they'll just look really ugly in other browsers).</p>
<p>Todos is a very simple to-do application. Users can CRUD tasks, and mark them as complete.
The source is <a href="http://github.com/maccman/spine.todos">available on GitHub</a>. <a href="http://maccman.github.com/spine.todos">[Demo]</a>
<img src="https://lh4.googleusercontent.com/_IH1OempnqUc/TZF16JZSTlI/AAAAAAAABKM/ojAu7OBqXp8/s500/Screen%20shot%202011-03-29%20at%2019.01.44.png" alt="Spine Todos" /></p>
<p>Spine contacts is a simple address book, allowing users to CRUD contacts. The full source is <a href="http://github.com/maccman/spine.contacts">available on GitHub</a>. <em>WebKit only</em>. <a href="http://maccman.github.com/spine.contacts">[Demo]</a>
<img src="https://lh5.googleusercontent.com/_IH1OempnqUc/TZpgYfnlUBI/AAAAAAAABKg/UYLhdmoc15o/s500/contacts.png" alt="Spine Contacts" /></p>
<p>Holla is the most advanced example, and <a href="http://github.com/maccman/holla">can be found on GitHub</a>. Holla is a group chat application, and uses a combination of <a href="http://rubyonrails.org">Rails</a>, <a href="http://github.com/maccman/juggernaut">Juggernaut</a> and Spine to let users chat in realtime. <em>WebKit only</em>. <a href="http://maccman-holla.heroku.com">[Demo]</a>
<img src="https://lh4.googleusercontent.com/_IH1OempnqUc/TZF1gMnidmI/AAAAAAAABKE/b9rp9RdtA3o/s500/Screen%20shot%202011-03-29%20at%2018.58.12.png" alt="Holla" /></p>
<h1>Setup</h1>
<p>Using Spine is very straightforward, simply include the library in the page.</p>
<pre><code><script src="spine.js" type="text/javascript" charset="utf-8"></script>
</code></pre>
<p>Spine has no prerequisites, but is optimized to work with <a href="http://jquery.com">jQuery</a> or <a href="http://zeptojs.com">Zepto</a>.
Certain extensions to Spine, such as the Ajax and Local Storage model persistence, require additional files located inside the <a href="https://github.com/maccman/spine/tree/master/lib">lib</a> folder.</p>
<h1>Classes</h1>
<p>Spine's class implementation is one of its features that makes it stand out from the crowd. Rather than copying properties to emulate inheritance, as most libraries, Spine uses JavaScript's native prototypal inheritance. This is how inheritance should be done, and means it's dynamic, properties are resolved at runtime.</p>
<p>Classes are created like so:</p>
<pre><code>var Task = Spine.Class.create();
</code></pre>
<p><code>create()</code> takes optional arguments of instance properties, and class properties.</p>
<pre><code>Spine.Class.create([instanceProperties, classProperties]);
var User = Spine.Class.create({
name: "Carolin"
});
</code></pre>
<p>Alternatively you can add instance properties using <code>include()</code>, and class properties with <code>extend()</code>.</p>
<pre><code>var User = Spine.Class.create();
User.extend({
find: function(){ /* ... */ }
});
User.include({
name: "Tonje"
});
</code></pre>
<p>Since Spine doesn't use constructor functions, due to limitations with prototypal inheritance, classes are instantiated with <code>init()</code>.</p>
<pre><code>var User = Spine.Class.create({
name: "Tonje"
});
var user = User.init();
assertEqual( user.name, "Tonje" );
user.name = "Trish";
assertEqual( user.name, "Trish" );
</code></pre>
<p>Any arguments passed to <code>init()</code> will be forwarded to <code>init()</code>, the classes' instantiation callback.</p>
<pre><code>var User = Spine.Class.create({
init: function(name){
this.name = name;
}
});
User.init("Martina");
assertEqual( user.name, "Martina" );
</code></pre>
<p>Sub-classes are created the same way base classes are, with <code>create()</code>.</p>
<pre><code>var Friend = User.create();
</code></pre>
<p>All of the subclass's parent properties are inherited.</p>
<pre><code>var friend = Friend.init("Tim");
assertEqual( friend.name, "Tim" );
</code></pre>
<p>Because we're using real prototypal inheritance, properties are resolved dynamically at runtime. This means that you can change the properties of a parent class, and all its sub-classes with reflect those changes immediately.</p>
<pre><code>var User = Spine.Class.create();
var Friend = User.create();
User.include({defaultName: "(empty)"});
assertEqual( Friend.init().defaultName, "(empty)" );
</code></pre>
<h2>Context</h2>
<p>Context changes constantly in JavaScript, and it's very important your code is executing in the correct one. The most common cause of this is with event listeners, where callbacks will be invoked in the context of <code>window</code> or the element, rather than their original context. To resolve this, Spine's classes provides a few helper functions for maintaing context.</p>
<p>You can pass a function to <code>proxy()</code> to guarantee that it will be invoked in the current context.</p>
<pre><code>var Tasks = Spine.Class.create({
init: function(){
$("#destroy").click(this.proxy(this.destroy));
},
destroy: function(){ /* ... */ }
});
</code></pre>
<p>Or pass multiple function names to <code>proxyAll()</code> in order to re-write them permanently, so they're always called with the classes' local content.</p>
<pre><code>var Tasks = Spine.Class.create({
init: function(){
this.proxyAll("destroy")
$("#destroy").click(this.destroy);
},
destroy: function(){ /* ... */ }
});
</code></pre>
<h1>Events</h1>
<p><code>Spine.Events</code> is the module Spine uses for adding event support to classes. To use it, just include/extend a class with the module.</p>
<pre><code>var Tasks = Spine.Class.create();
Tasks.extend(Spine.Events);
</code></pre>
<p><code>Spine.Events</code> gives you three functions, <code>bind()</code>, <code>trigger()</code>, and <code>unbind()</code>. All three have a very similar API to jQuery's event handling one, if you're familiar with that. <code>bind(name, callback)</code> takes a event name and callback. <code>trigger(name, [*data])</code> takes an event name and optional data to be passed to handlers. <code>unbind(name, [callback])</code> takes a event name and optional callback.</p>
<pre><code>Tasks.bind("create", function(){ /* ... */ });
Tasks.trigger("create", ["some", "data"]);
</code></pre>
<p>You can bind to multiple events by separating them with spaces. Callbacks are invoked in the context the event is associated with.</p>
<pre><code>Tasks.bind("create update destroy", function(){ this.trigger("change") });
</code></pre>
<p>You can pass optional data arguments to <code>trigger()</code> that will be passed onto event callbacks. Unlike jQuery, an event object will not be passed to callbacks.</p>
<pre><code>Tasks.bind("create", function(name){
alert(name);
});
Tasks.trigger("create", "Take out the rubbish");
</code></pre>
<p>Although you may never use <code>Spine.Events</code> in your own classes, you will use it with Spine's models and controllers. We're going to cover those next.</p>
<h1>Models</h1>
<p>Models are the core to Spine, and absolutely critical to your applications. Models are where your application's data is stored, and where any logic associated with that data is kept. Models should be de-coupled from the rest of your application, and completely independent. The data associated with models is stored in memory under <code>Model.records</code>.</p>
<p>Creating models is slightly different from creating classes, since the <code>create()</code> function is already reserved by models. Models are created with the <code>setup()</code> function, passing in the model name and an array of attributes.</p>
<pre><code>var Contact = Spine.Model.setup("Contact", ["first_name", "last_name"]);
</code></pre>
<p>Models are Spine classes, so you can treat them as such, extending and including properties.</p>
<pre><code>Contact.include({
fullName: function(){
return(this.first_name + " " + this.last_name);
}
});
</code></pre>
<p>Model instances are created with <code>init()</code>, passing in an optional set of attributes.</p>
<pre><code>var contact = Contact.init({first_name: "Alex", last_name: "MacCaw"});
assertEqual( contact.fullName(), "Alex MacCaw" );
</code></pre>
<h2>Saving/Retrieving Records</h2>
<p>Once an instance is created it can be saved in memory by calling <code>save()</code>.</p>
<pre><code>var Contact = Spine.Model.setup("Contact", ["first_name", "last_name"]);
var contact = Contact.init({first_name: "Joe"});
contact.save();
</code></pre>
<p>When a record is saved, Spine automatically creates an ID if it doesn't already exist.</p>
<pre><code>assertEqual( contact.id, "AD9408B3-1229-4150-A6CC-B507DFDF8E90" );
</code></pre>
<p>You can use this ID to retrieve the saved record using <code>find()</code>.</p>
<pre><code>var identicalContact = Contact.find( contact.id );
assert( contact.eql( identicalContact ) );
</code></pre>
<p>If <code>find()</code> fails to retrieve a record, an exception will be thrown. You can check for the existence of records without fear of an exception by calling <code>exists()</code>.</p>
<pre><code>assert( Contact.exists( contact.id ) );
</code></pre>
<p>Once you've changed any of a record's attributes, you can update it in-memory by re-calling <code>save()</code>.</p>
<pre><code>var contact = Contact.create({first_name: "Polo"});
contact.save();
contact.first_name = "Marko";
contact.save();
</code></pre>
<p>You can also use <code>first()</code> or <code>last()</code> on the model to retrieve the first and last records respectively.</p>
<pre><code>var firstContact = Contact.first();
</code></pre>
<p>To retrieve every contact, use <code>all()</code>.</p>
<pre><code>var contacts = Contact.all();
for (var i=0; i < contacts.length; i++)
console.log( contacts[i].first_name );
</code></pre>
<p>You can pass a function that'll be iterated over every record using <code>each()</code>.</p>
<pre><code>Contact.each(function(con){
console.log( con.first_name );
});
</code></pre>
<p>Or select a subset of records with <code>select()</code>.</p>
<pre><code>Contact.select(function(con){
if (con.first_name) return true;
});
</code></pre>
<h2>Validation</h2>
<p>Validating models is dirt simple, simply override the <code>validate()</code> function with your own custom one.</p>
<pre><code>Contact.include({
validate: function(){
if (!this.first_name)
return "First name is required";
}
});
</code></pre>
<p>If <code>validate()</code> returns anything, the validation will fail and an <em>error</em> event will be fired on the model. You can catch this by listening for it on the model, notifying the user.</p>
<pre><code>Contact.bind("error", function(rec, msg){
alert("Contact failed to save - " + msg);
});
</code></pre>
<p>In addition, <code>save()</code>, <code>create()</code> and <code>updateAttributes()</code> will all return false if validation fails. For more information about validation, see the <a href="http://maccman.github.com/spine.tutorials/form.html">form tutorial</a>.</p>
<h2>Serialization</h2>
<p>Spine's models include special support for JSON serialization. To serialize a record, call <code>JSON.stringify()</code> passing the record, or to serialize every record, pass the model.</p>
<pre><code>JSON.stringify(Contact);
JSON.stringify(Contact.first());
</code></pre>
<p>Alternatively, you can retrieve an instance's attributes and implement your own serialization by calling <code>attributes()</code>.</p>
<pre><code>var contact = Contact.init({first_name: "Leo"});
assertEqual( contact.attributes(), {first_name: "Leo"} );
Contact.include({
toXML: function(){
return serializeToXML(this.attributes());
}
});
</code></pre>
<p>If you're using an older browser which doesn't have native JSON support (i.e. IE 7), you'll need to include <a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js">json2.js</a> which adds legacy support.</p>
<h2>Persistence</h2>
<p>While storing records in memory is useful for quick retrieval, persisting them in one way or another is often required. Spine includes a number of pre-existing storage modules, such as Ajax and HTML5 Local Storage, which you can use for persistence. Alternatively you can roll your own custom one, take a look at <code>spine.ajax.js</code> for inspiration.</p>
<p>Spine's persistence is implemented via modules, so for HTML5 Local Storage persistence you'll need to include <a href="lib/spine.local.js">spine.local.js</a> script in the page and for Ajax persistence you'll need <a href="lib/spine.ajax.js">spine.ajax.js</a>.</p>
<p>To persist a model using HTML5 Local Storage, simply extend it with <code>Spine.Model.Local</code>.</p>
<pre><code>Contact.extend(Spine.Model.Local);
</code></pre>
<p>When a record is changed, the Local Storage database will be updated to reflect that. In order to fetch the records from Local Storage in the first place, you need to use <code>fetch()</code>.</p>
<pre><code>Contact.fetch();
</code></pre>
<p>Typically this is called once, when your application is first initialized.</p>
<h3>Using Ajax</h3>
<p>Using Ajax as a persistence mechanism is very similar, extend models with <code>Spine.Model.Ajax</code>.</p>
<pre><code>Contact.extend(Spine.Model.Ajax);
</code></pre>
<p>By convention, this uses a basic pluralization mechanism to generate an endpoint, in this case <code>/contacts</code>. You can choose a custom URL by setting the <code>url</code> property on your model, like so:</p>
<pre><code>Contact.extend({
url: "/users"
});
</code></pre>
<p>Spine will use this endpoint URL as a basis for all of its Ajax requests. Once a model has been persisted with Ajax, whenever its records are changed, Spine will send an Ajax request notifying the server. Spine encodes all of its request's parameters with JSON, and expects JSON encoded responses. Spine uses REST to determine the method and endpoint of HTTP requests, and will work seamlessly with REST friendly frameworks like Rails.</p>
<pre><code>read → GET /collection
create → POST /collection
update → PUT /collection/id
destroy → DELETE /collection/id
</code></pre>
<p>For example, after a record has been created client side Spine will send off an HTTP POST to your server, including a JSON representation of the record. Let's say we created a <code>Contact</code> with a name of <code>"Lars"</code>, this is the request that would be send to the server:</p>
<pre><code>POST /contacts HTTP/1.0
Host: localhost:3000
Origin: http://localhost:3000
Content-Length: 59
Content-Type: application/json
{"id":"E537616F-F5C3-4C2B-8537-7661C7AC101E","name":"Lars"}
</code></pre>
<p>Likewise destroying a record will trigger a DELETE request to the server, and updating a record will trigger a PUT request. For PUT and DELETE requests, the records ID is referenced inside the URL.</p>
<pre><code>PUT /tasks/E537616F-F5C3-4C2B-8537-7661C7AC101E HTTP/1.0
Host: localhost:3000
Origin: http://localhost:3000
Content-Length: 60
Content-Type: application/json
{"id":"44E1DB33-2455-4728-AEA2-ECBD724B5E7B","name":"Peter"}
</code></pre>
<p>As you can see, the record's attributes aren't prefixed by the record's model name. This can cause problems with frameworks like Rails, which expect parameters in a certain format. You can fix this, by setting the <code>ajaxPrefix</code> option.</p>
<pre><code>Spine.Model.ajaxPrefix = true;
</code></pre>
<p>If <code>ajaxPrefix</code> is true, Spine will send requests like the following, prefixing all the attributes with the model name.</p>
<pre><code>PUT /tasks/E537616F-F5C3-4C2B-8537-7661C7AC101E HTTP/1.0
Host: localhost:3000
Origin: http://localhost:3000
Content-Length: 73
Content-Type: application/json
{"contact": {"id":"44E1DB33-2455-4728-AEA2-ECBD724B5E7B","name":"Peter"}}
</code></pre>
<p>It's worth mentioning here one of the major differences between Spine and other similar frameworks. All of Spine's server communication is asynchronous - that is Spine never waits for a response. Requests are sent after the operation has completed successfully client side. In other words, a POST request will be sent to the server after the record has successfully saved client side, and the UI has updated. The server is completely de-coupled from the client, clients don't necessarily need a server in order to function.</p>
<p>This might seem like an odd architectural decision at first, but let me explain. Having a de-coupled server offers some clear advantages. Firstly, clients have a completely non-blocking interface, they're never waiting for a slow server response for further interaction with your application. User's don't have to know, or care, about server requests being fired off in the background - they can continue using the application without any loading spinners.</p>
<p>The second advantage is that a de-coupled server greatly simplifies your code. You don't need to cater for the scenario that the record may be displayed in your interface, but isn't editable until a server response returns. Lastly, if you ever decided to add offline support to your application, having a de-coupled server makes this a doddle.</p>
<p>Obviously there are caveats for those advantages, but I think those are easily addressed. Server-side model validation is a contentious issue, for example - what if that fails? However, this is solved by client-side validation. Validation should fail before a record ever gets sent to the server. If validation does fail server-side, it's an error in your client-side validation logic rather than with user input.</p>
<p>When the server does return an unsuccessful response, an <em>ajaxError</em> event will be fired on the model, including the record, XMLHttpRequest object, Ajax settings and the thrown error.</p>
<pre><code>Contact.bind("ajaxError", function(record, xhr, settings, error){
/* Invalid response... */
});
</code></pre>
<h2>Events</h2>
<p>You've already seen that models have some events associated with them, such as <em>error</em> and <em>ajaxError</em>, but what about callbacks to create/update/destroy operations? Well, conveniently Spine includes those too, allowing you to bind to the following events:</p>
<ul>
<li><em>save</em> - record was saved (either created/updated)</li>
<li><em>update</em> - record was updated</li>
<li><em>create</em> - record was created</li>
<li><em>destroy</em> - record was destroyed</li>
<li><em>change</em> - any of the above, record was created/updated/destroyed</li>
<li><em>refresh</em> - all records invalidated and replaced</li>
<li><em>error</em> - validation failed</li>
</ul>
<p>For example, you can bind to a model's <em>create</em> event like so:</p>
<pre><code>Contact.bind("create", function(newRecord){
// New record was created
});
</code></pre>
<p>For model level callbacks, any associated record is always passed to the callback. The other option is to bind to the event directly on the record.</p>
<pre><code>var contact = Contact.first();
contact.bind("save", function(){
// Contact was updated
});
</code></pre>
<p>The callback's context will be the record that the event listener was placed on. You'll find model events crucial when it comes to binding records to the view, making sure the view is kept in sync with your application's data.</p>
<h2>Dynamic records</h2>
<p>One rather neat addition to Spine's models is dynamic records, which use prototypal inheritance to stay updated. Any calls to <code>find()</code>, <code>all()</code>, <code>first()</code>, <code>last()</code> etc, and model event callbacks return a <em>clone</em> of the saved record. This means that whenever a record is updated, all of its clones will immediately reflect that update.</p>
<p>Let's give you a code example; we're going to create an asset, and a clone of that asset. You'll notice that when the asset is updated, the clone has also automatically changed.</p>
<pre><code>var asset = Asset.create({name: "whatshisname"});
// Completely new asset instance
var clone = Asset.find(asset.id);
// Change saved asset
asset.updateAttributes({name: "bob"});
// Clone reflects changes
assertEqual(clone.name, "bob");
</code></pre>
<p>This means that you never have to bother calling some sort of <code>reload()</code> functions on instances. You can be sure that all instances are constantly in sync with their saved versions.</p>
<h1>Controllers</h1>
<p>Controllers are the last part to the trinity of Spine and are very simple, being more of a set of conventions than actual code. Controllers are the glue inside your application, tying the various components together. Generally, controllers deal with adding and responding to DOM events, rendering templates and keeping views and models in sync.</p>
<p>Controllers, like models, extend <code>Spine.Class</code> and so inherit all of its properties. This means you can use <code>extend()</code> and <code>include()</code> to add properties onto controllers, and can take advantage of all of Spine's context management. To create a controller, inherit a class from <code>Spine.Controller</code>.</p>
<pre><code>var Tasks = Spine.Controller.create({
init: function(){
// Called on instantiation
}
});
</code></pre>
<p>The convention inside Spine is to give the controller a plural camel cased name of the model it is most associated with, in this case <code>Tasks</code>. Usually, you'll only be adding instance properties onto controllers, so you can just pass them as the first argument to <code>create()</code>. Instantiating controllers is the same as creating an instance of any other class, by calling <code>init()</code>.</p>
<pre><code>var tasks = Tasks.init();
</code></pre>
<p>Every controller has an element associated with it, which you can access under the instance property <code>el</code>. You can also set this element manually by passing it through on instantiation.</p>
<pre><code>var tasks = Tasks.init({el: $("#tasks")});
</code></pre>
<p>In fact, anything you pass to <code>init()</code> will be set as properties on the newly created instance. For example, you could pass a record that a controller would be associated with.</p>
<pre><code>var taskItem = TaskItem.init({item: Task.first()});
</code></pre>
<p>Inside your controller's <code>init()</code> function, you'll generally add event listeners to models and views, referencing a function inside the controller.</p>
<h2>Events</h2>
<p>Spine gives you a shortcut for adding event listeners onto DOM elements, with the <code>events</code> property.</p>
<pre><code>var Tasks = Spine.Controller.create({
events: {"click .item": "click"},
click: function(e){
// Invoked when .item is clicked
}
});
</code></pre>
<p><code>events</code> is an object in the following format <code>{"eventType selector", "functionName"}</code>. All the selectors are scoped to the controller's associated element, <code>el</code>. If a selector isn't provided, the event will be added directly on <code>el</code>, otherwise it'll be delegated to any children matching the selector.</p>
<p>Spine will take care of callback context for you, making sure it keeps to the current controller. Callbacks will be passed an event object, and you can access the original element the event was targeted on using <code>event.target</code>.</p>
<pre><code>var Tasks = Spine.Controller.create({
events: {"click .item": "click"},
click: function(event){
var item = jQuery(event.target);
}
});
</code></pre>
<p>Since Spine uses <a href="http://api.jquery.com/delegate">delegation</a> for events, it doesn't matter if the contents of <code>el</code> change. The appropriate events will still be fired when necessary.</p>
<p>As well as DOM events, <code>Spine.Controller</code> has been extended with <code>Spine.Events</code>, meaning that you can bind and trigger custom events.</p>
<pre><code>var ToggleView = Spine.Controller.create({
init: function(){
this.items = this.$(".items");
this.items.click(this.proxy(function(){
this.trigger("toggle");
}));
this.bind("toggle", this.toggle);
},
toggle: function(){ /* ... */ }
});
</code></pre>
<p>Spine also has a global object <code>Spine.App</code>, that you can bind and trigger global events. This is one way that you can get controllers communicating with one other, without resorting to deep-coupling. <code>Spine.App</code> is aliased inside controllers to <code>this.App</code>.</p>
<pre><code>var GlobalController = Spine.Controller.create({
init: function(){
this.el.click(this.proxy(this.click));
},
click: function(){
this.App.trigger("globalEvent", this.el);
}
});
</code></pre>
<h2>Elements</h2>
<p>When you first instantiate a controller, it's common to set a bunch of instance variables referencing various elements. For example, setting the <code>items</code> variable on the <code>Tasks</code> controller:</p>
<pre><code>var Tasks = Spine.Controller.create({
init: function(){
this.items = this.$(".items");
}
});
</code></pre>
<p>Since this is such a common scenario, Spine provides a helper, the <code>elements</code> property. The is in the format of <code>{"selector": "variableName"}</code>. When the controller is instantiated, Spine will go through <code>elements</code>, setting the appropriate elements as properties on the instance. Like with <code>events</code>, all the selectors are scoped by the controller's current element, <code>el</code>.</p>
<pre><code>var Tasks = Spine.Controller.create({
elements: {".items": "items"},
init: function(){
this.items.each(function(){
// ...
});
}
});
</code></pre>
<h2>Proxying</h2>
<p>Setting up a bunch of proxies in your controller's <code>init()</code> function is also a common scenario. For example:</p>
<pre><code>var Tasks = Spine.Controller.create({
init: function(){
this.proxyAll("render");
Task.change(this.render);
},
render: function(){ /* ... */ }
});
</code></pre>
<p>As you've probably guessed, Spine provides a shortcut for adding proxies too, using the <code>proxied</code> property. Simply set <code>proxied</code> to an array of function names, and Spine will make sure those functions are always executed in the controller's context.</p>
<pre><code>var Tasks = Spine.Controller.create({
proxied: ["render"],
init: function(){
Task.change(this.render);
}
});
</code></pre>
<h1>Routing</h1>
<p>Spine provides application routing based on the URL's hash fragment, for example the URL <code>http://example.com/#/users</code> has the hash fragment <code>/users</code>. Hash fragments can be completely arbitrary and don't trigger page reloads, maintaining page state. Your application can also be indexed by hash fragments using Google's <a href="http://code.google.com/web/ajaxcrawling/index.html">Ajax Crawling specification</a>.</p>
<p>Internally Spine uses the <em>hashchange</em> event to detect changes in the URLs hash. This event has only been developed recently, and only available in newer browsers. To support antiquated browsers, you can use the excellent <a href="http://benalman.com/projects/jquery-hashchange-plugin/">jQuery hashchange plugin</a>, which emulates the event using iframes and other clever trickery.</p>
<h2>Adding routes</h2>
<p>So, how to use the API? It's very simple, first you need to include <a href="lib/spine.route.js">spine.route.js</a>, which contains the module <code>Spine.Route</code>. Then you can start adding routes inside your controller. <code>Spine.Route</code> gives you a <code>routes()</code> function inside controllers, which you can call passing a hash of routes and callbacks.</p>
<pre><code>var App = Spine.Controller.create({
init: function(){
this.routes({
"/users/:id": function(id){
// Activate controller or something
console.log("/users/", id)
},
"/users": function(any){
console.log("/users")
}
});
}
}).init();
</code></pre>
<p>Route parameters, are in the form of <code>:name</code>, and are passed as arguments to the associated callback. You can also use globs to match anything via an asterisk, like so:</p>
<pre><code>App.routes({
"/pages/*glob": function(name){
console.log("/pages/", name);
}
});
</code></pre>
<p>Routes are added in reverse order of specificity, so the most specific routes should be added first, and generic 'catch alls' should be added later. It's worth noting, especially if you're putting routes in the <code>init()</code> function of controllers, that routes shouldn't be added more than once. The examples above are fine, since the <code>App</code> controller is only ever going to be instantiated a single time.</p>
<p>One alternative is to skip out controllers, and add routes directly using <code>Spine.Route.add()</code>, passing in either a hash or a single route.</p>
<pre><code>Spine.Route.add(/\/groups(\/)?/, function(){
console.log('groups')
});
</code></pre>
<p>Like you can see in the example above, routes can also be raw regexes, giving you full control over matching.</p>
<h2>Initial Setup</h2>
<p>When the page loads initially, even if the URL has a hash fragment, the <code>hashchange</code> event won't be called. It'll only be called for subsequent changes. This means, after our application has been setup, we need to manually tell Spine that we want to run the routes & check the URL's hash. This can be done by invoking <code>Spine.Route.setup()</code>.</p>
<pre><code>Spine.Route.setup();
</code></pre>
<h2>Navigate</h2>
<p>Lastly, Spine gives controllers a <code>navigate()</code> function, which can be passed a fragment to change the URL's hash. You can also pass <code>navigate()</code> multiple arguments, which will be joined by a forward slash (<code>/</code>) to create the fragment.</p>
<pre><code>var Users = Spine.Controller.create({
init: function(){
// Navigate to #/users/:id
this.navigate("/users", this.item.id);
}
});
Users.init({item: User.first()});
</code></pre>
<p>Using <code>navigate()</code> ensures that the URL's fragment is kept in sync with the relevant controllers. By default, calling <code>navigate()</code> <strong>won't</strong> trigger any events or route callbacks. If you want to trigger routes, pass a <code>true</code> boolean as the last argument to <code>navigate()</code>.</p>
<pre><code>// Trigger routes by passing true
Spine.Route.navigate("/users", true);
</code></pre>
<h2>HTML5 History</h2>
<p>Spine also gives you the option of using HTML5's History API, which has the advantage of being able to alter the url without a page refresh or using hash fragments. This means cleaner URLs in a format your users are accustomed to.</p>
<p>To use the History API, instead of hash fragments, pass <code>{history: true}</code> to <code>setup()</code>:</p>
<pre><code>Spine.Route.setup({history: true});
</code></pre>
<p>HTML5 History support will only be enabled if this option is present, and the API is available. Otherwise, Spine's routing will revert back to using hash fragments.</p>
<p>However, there are some things you need to be aware of when using the History API. Firstly, ever URL you send to <code>navigate()</code> needs to have a real HTML representation. Although the browser won't request the new URL at that point, it will be requested if the page is subsequently reloaded. In other words you can't make up arbitrary URLs, like you can with hash fragments; every URL passed to the API needs to exist. One way of implementing this is with server side support.</p>
<p>When browsers request a URL (expecting a HTML response) you first make sure on server-side that the endpoint exists and is valid. Then you can just serve up the main application, which will read the URL, invoking the appropriate routes. For example, let's say your user navigates to <code>http://example.com/users/1</code>. On the server-side, you check that the URL <code>/users/1</code> is valid, and that the User record with an ID of <code>1</code> exists. Then you can go ahead and just serve up the JavaScript application.</p>
<p>The caveat to this approach is that it doesn't give search engine crawlers any real content. If you want your application to be crawl-able, you'll have to detect crawler bot requests, and serve them a 'parallel universe of content'. That is beyond the scope of this documentation though.</p>
<h1>Patterns</h1>
<p>We've covered all the main options available in controllers, so let's have a look at some typical use cases.</p>
<h2>The Render Pattern</h2>
<p>The <em>render pattern</em> is a really useful way of binding models and views together. When the controller is instantiated, it adds an event listener to the relevant model, invoking a callback when the model is refreshed or changed. The callback will update <code>el</code>, usually by replacing its contents with a rendered template.</p>
<pre><code>var Contacts = Spine.Controller.create({
init: function(){
Contact.bind("refresh change", this.proxy(this.render));
},
template: function(items){
return($("#contactsTemplate").tmpl(items));
},
render: function(){
this.el.html(this.template(Contact.all()));
}
});
</code></pre>
<p>This is a simple but blunt method for data binding, updating every element whenever a single record is changed. This is fine for uncomplicated and small lists, but you may find you need more control over individual elements, such as adding event handlers to items. This is where the <em>element pattern</em> comes in.</p>
<h2>The Element pattern</h2>
<p>The element pattern essentially gives you the same functionality as the render pattern, but a lot more control. It consists of two controllers, one that controls a collection of items, and the other deals with each individual item. Let's dive right into the code to give you a good indication of how it works.</p>
<pre><code>var ContactItem = Spine.Controller.create({
// Delegate the click event to a local handler
events: {
"click": "click"
},
// Ensure functions have the correct context
proxied: ["render", "remove"],
// Bind events to the record
init: function(){
this.item.bind("update", this.render);
this.item.bind("destroy", this.remove);
},
// Render an element
render: function(item){
if (item) this.item = item;
this.el.html(this.template(this.item));
return this;
},
// Use a template, in this case via jQuery.tmpl.js
template: function(items){
return($("#contactsTemplate").tmpl(items));
},
// Called after an element is destroyed
remove: function(){
this.el.remove();
},
// We have fine control over events, and
// easy access to the record too
click: function(){ /* ... */ }
});
var Contacts = Spine.Controller.create({
proxied: ["addAll", "addOne"],
init: function(){
Contact.bind("refresh", this.addAll);
Contact.bind("create", this.addOne);
},
addOne: function(item){
var contact = ContactItem.init({item: item});
this.el.append(contact.render().el);
},
addAll: function(){
Contact.each(this.addOne);
}
});
</code></pre>
<p>In the example above, <code>Contacts</code> has responsibility for adding records when they're initially created, and <code>ContactItem</code> has responsibility for the record's update and destroy events, re-rendering the record when necessary. Albeit more complicated, this gives us some advantages over the previous render pattern.</p>
<p>For one thing, it's more performant; the list doesn't need to be re-drawn whenever a single element changes. Furthermore, we now have a lot more control over individual items. We can place event handlers, as demonstrated with the <code>click</code> callback, and manage rendering on an item by item basis.</p>
<h1>Resources</h1>
<p>All resources are located in the <em>lib</em> folder in Spine's repository.</p>
<ul>
<li><em>lib/spine.list.js</em> - controller for managing lists, such as menus</li>
<li><em>lib/spine.manager.js</em> - class for managing controllers, basically a state machine</li>
<li><em>lib/spine.ajax.js</em> - module for adding Ajax support to Spine's models</li>
<li><em>lib/spine.local.js</em> - module for adding Local Storage support to Spine's models</li>
<li><em>lib/spine.route.js</em> - module for adding route support to Spine</li>
</ul>
<p>Any questions, just ask on the <a href="https://groups.google.com/forum/?hl=en#!forum/spinejs">Google Group</a>.<br/>
Found a bug? Open a <a href="https://github.com/maccman/spine/issues">ticket on GitHub</a>.</p>
<p>Spine has a full Jasmine test suite - you can run it from inside the browser <a href="test/index.html">here</a>.</p>
<h1>FAQ</h1>
<ul>
<li><p><em>Whoah - your API looks really similar to Backbone. Why should I use this instead?</em>
Well, it's true that Spine was inspired by Backbone, an excellent library, and its controller API is very similar. However, the similarities end there. Internally the library works very differently. For example, Spine has no need for <code>Collections</code>, which are required for pretty much every model in Backbone. Spine provides a class library, and has very different ideas when it comes to server sync. Lastly, Spine is much simpler and half the size, go and <a href="http://github.com/maccman/spine">check out the source</a>.</p></li>
<li><p><em>What's so good about prototypal inheritance?</em>
Let me give you a visual example of what I mean. Take a Spine class instance, you can follow its <code>__proto__</code> property through its parents, all the way up to <code>Object</code>.
<img src="site/images/inheritance.png" alt="Inheritance" /><br/>
Classical class libraries just copy properties to achieve inheritance, resulting in overhead when your class is first loaded, and doesn't allow for dynamically resolving properties.</p></li>
<li><p><em>Doesn't the fact that servers are de-coupled, and clients never wait for a response, cause issues like conflicts?</em>
Nope, certainly not in my experience. Ajax requests to the server are sent serially, requests have to finish before the next one is fired, even if the client UI has already updated. For example, if a contact is created and then immediately destroyed, the create POST will complete before the DELETE request is sent. Certainly, there may be scenarios where you need to disable a UI element while waiting for a server response, but this isn't usually required, and so isn't the default inside Spine.</p></li>
<li><p><em>I still don't get the advantages of server de-coupling.</em>
Well, it's all about perceived speed - which makes a huge difference to the user experience. Perceived speed is just as important as actual speed since, at the end of the day, this is what users are going to notice. If we take <a href="http://github.com/maccman/holla">Holla</a> as an example, when a user sends a new chat message, we could wait until the message takes the roundtrip through the server and clients before appending it to the chat log. However, that would introduce a couple of seconds latency between the time a user submitted a new message, and it appearing in their chat log. The application would seem slow, and it would definitely hurt the user experience.</p>
<p>Instead, why not create the new message locally, thereby immediately adding it to the chat log. From a user's perspective, it seems like the message has been sent instantly. User's won't know (or care), that the message hasn't yet been delivered to other clients in the chat room. They'll just be happy with a fast and snappy user experience.</p>
<p>That's why server de-coupling and perceived speed is important, <strong>it gives a much better user experience</strong>.</p></li>
</ul>
<h1>Change Log</h1>
<p><strong>0.0.2:</strong> 17/04/2011 - first public release<br/>
<strong>0.0.3:</strong> 25/04/2011 - IE support, tests and fixes<br/>
<strong>0.0.4:</strong> 11/05/2011 - Spine.Manager, Spine.List and Spine.Tabs</p>
<script type="text/javascript" charset="utf-8">
jQuery(function($){
function dasherize(str) {
return str.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
.replace(/([a-z\d])([A-Z])/g, '$1-$2')
.replace(/\s/g, '-')
.toLowerCase();
}
var sidebar = $("<div />").attr("id", "sidebar");
$("h1").each(function(){
var name = $(this).text();
$(this).attr("id", "h-" + dasherize(name));
sidebar.append(
$("<a />").attr("href", "#" + $(this).attr("id")).text(name)
)
var subs = $(this).nextUntil("h1").filter("h2");
if( subs.length > 0 ) {
var list = $("<ul />");
subs.each(function(){
var subName = $(this).text();
$(this).attr("id", "s-" + dasherize(name) + '-' + dasherize(subName));
list.append(
$("<li />").append(
$("<a />").text(subName).attr("href", "#" + $(this).attr("id"))
)
)
});
sidebar.append(list);
}
});
$("body").prepend(sidebar);
});
</script>
</div>
</body>
</html>