-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathapi.html.eco
More file actions
executable file
·1319 lines (1244 loc) · 49 KB
/
api.html.eco
File metadata and controls
executable file
·1319 lines (1244 loc) · 49 KB
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
layout : 'default'
css : 'api'
standalone : true
element : 'API'
elementType : 'behavior'
title : 'API'
description : 'API allows elements to trigger actions on a server'
type : 'UI Behavior'
---
<script src="/javascript/library/serialize-object.js"></script>
<script src="/javascript/api.js"></script>
<%- @partial('header', { tabs: { overview: 'Overview', usage: 'Usage', behaviors: 'Behaviors', settings: 'Settings' } }) %>
<div class="main ui container">
<div class="ui active intro tab" data-tab="overview">
<div class="test example">
<h4 class="ui header">Integrates Seamlessly with UI</h4>
<p>API is designed to make the process of integrating data sources to UI components seamless, <a href="#api-state-management">tying API request state</a> to UI states automatically.</p>
<p>For example adding an API behavior to an <a href="/elements/input.html"><code>input</code></a> will occur <code>oninput</code>, while a <a href="/elements/button.html"><code>button</code></a>, will query the server <code>onclick</code>.</p>
<div class="ui icon input">
<i class="search icon"></i>
<input type="text" placeholder="Type here...">
</div>
<div class="ui hidden divider"></div>
<div class="ui primary button">Click Me</div>
<div class="ui disabled button">Disabled</div>
</div>
<div class="no example">
<h4 class="ui header">Preserve Templated URLs</h4>
<p>API helps you decouple URLs from your code. Use named API actions like <code>get followers</code> instead of URLs like <code>http://foo.com/get/1.0/followers.json</code> in your code.</p>
<div class="ignored code" data-type="javascript">
$('.button')
.api({
action: 'get followers'
})
;
</div>
<p>Centrally manage your entire API making sure you aren't caught modifying urls across your codebase. Define your endpoints using an <a href="#api-actions">intuitive templating system</a> that <a href="#passing-data">automatically passes data</a> found in your UI.</p>
<div class="ignored code" data-type="javascript">
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}',
'create user' : '/create',
'add user' : '/add/{id}',
'search' : '/query/{query}/{/sort}'
};
</div>
</div>
<div class="no example">
<h4 class="ui header">HTTP 200 is Not Success</h4>
<p>Parse your JSON for <code>success</code> conditions before callbacks fire, making sure server errors caught correctly, still trigger error conditions in your front end code.</p>
<div class="ignored code">
// Responses without this status will trigger error conditions
$.fn.api.settings.successTest = function(response) {
return response.status == 'OK';
}
</div>
</div>
<div class="no example">
<h4 class="ui header">Translate APIs on the Fly</h4>
<p>Using a third party API that uses some unruly code? Not a problem! API lets you <a href="/introduction/new.html#translates-any-api">modify an APIs raw JSON response</a> before it is consumed by your code.</p>
</div>
<div class="no example">
<h4 class="ui header">Tools for Third-Party Integrations & Mocking</h4>
<p>New powerful callbacks like <a href="#fulfilling-responses"><code>response</code></a> and <a href="#using-custom-backends"><code>responseAsync</code></a> let you asynchronously mock responses and trigger the same callbacks as your API.</p>
</div>
</div>
<div class="ui intro tab" data-tab="usage">
<div class="fixed column">
<div class="demo content ui sticky">
<h4 class="ui sub header">API Example</h4>
<div class="ui fluid card">
<div class="image">
<img src="/images/avatar2/large/patrick.png">
</div>
<div class="content">
<a class="header">Patrick Russel</a>
<div class="description">Patrick lives in San Francisco, and studies french literature.</div>
</div>
<div class="ui bottom attached follow button" data-id="22">Follow</div>
</div>
</div>
</div>
<div class="examples">
<h2 class="ui dividing header">Creating an API</h2>
<div class="no example">
<h4 class="ui header">API Actions</h4>
<p><b>API</b> works by defining a set of server actions which interface elements can query. Actions are usually represented by short phrases, things like <code>save profile</code>, or <code>get followers</code> which correspond to a templated URL resource on the server.</p>
<p>URL variables specified in actions are substituted at run-time allowing individual components to query different URLs.</p>
<p>URLs listed in your API can include <b>required parameters</b> and <b>optional parameters</b> which may be adjusted for each call.</p>
</div>
<div class="no example">
<h4 class="ui header">Required Parameters</h4>
<div class="ui large bulleted list">
<div class="item">Uses format <code>{variable}</code></div>
<div class="item"><b>Will abort the request</b> if they cannot be found.</div>
</div>
<div class="code" data-type="javascript">
/* Two required variables */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}'
};
</div>
</div>
<div class="no example">
<h4 class="ui header">Optional Parameters</h4>
<div class="ui large bulleted list">
<div class="item">Uses format <code>{/variable}</code></div>
<div class="item">Will <b>not</b> abort the request if they cannot be found.</div>
<div class="item"><b>Will be removed</b> from the URL automatically if not available.</div>
<div class="item">Any preceding slash before an optional parameter will be removed from the URL, allowing you to include them in resource paths.</div>
</div>
<div class="code" data-type="javascript">
/* One required, one optional variable */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}/{/sort}'
};
</div>
</div>
<div class="no example">
<h4 class="ui header">Creating your API</h4>
<p>You should define your endpoints <b>once in your application</b>. Usually this is done in a central configuration file included on each page.</p>
<p>These named API endpoints are stored globally in <code>$.fn.api.settings.api</code>.</p>
<p>Keeping your endpoints defined in one place makes sure when you update your application you will only need to update a single location with new URLs.</p>
<div class="code" data-type="javascript">
/* Define API endpoints once globally */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}',
'create user' : '/create',
'add user' : '/add/{id}',
'follow user' : '/follow/{id}',
'search' : '/search/?query={value}'
};
</div>
</div>
<div class="no example">
<h4 class="ui header">Using URLs</h4>
<p>Named API actions are not required to use API, you can also manually specify the URL for a request and use the same templating:</p>
<div class="code">
$('.search.button')
.api({
url: 'http://www.google.com?q={value}'
})
;
</div>
</div>
<h2 class="ui dividing header">Querying API Actions</h2>
<div class="no example">
<div class="ui info message">
<p>The following examples work best while viewing <code>console</code> logs in your web console.</p>
</div>
<h4 class="ui header">Attaching API Events</h4>
<p>API events are triggered by attaching named actions to elements on your page. These actions look up named endpoints in your API translating templated values from your element for each call.</p>
<p>Any element can have an API action attached directly to it. By default the action will occur on the most appropriate event for the type of element. For example a button will call your server <code>onclick</code>, an input <code>oninput</code>, or a form <code>onsubmit</code>.</p>
<p>API actions and data can be specified in Javascript on initialization:</p>
<div class="code" data-type="html">
<div class="ui follow button">
Follow
</div>
</div>
<div class="evaluated code">
// translates '/follow/{id}' to 'follow/22'
$('.follow.button')
.api({
action: 'follow user',
urlData: {
id: 22
}
})
;
</div>
<div class="ui horizontal divider">Or</div>
<p>API actions and data can also be specified in metadata:</p>
<div class="code" data-type="html">
<div class="ui follow button" data-action="follow user" data-id="22">
Follow
</div>
</div>
<div class="code">
// also calls '/follow/22'
$('.follow.button')
.api()
;
</div>
</div>
<div class="no example">
<h4 class="ui header">Specifying DOM Events</h4>
<p>If you need to override what action an API event occurs on you can use the <code>on</code> parameter.</p>
<div class="ui message">
API requests for the following demos have been faked using API's <code>response</code> setting to avoid rate throttling from public APIs. No actual data is returned.
</div>
<div class="code" data-demo="true">
$('.follow.button')
.api({
action: 'follow user',
on: 'mouseenter'
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">Calling Immediately</h4>
<p>If you require API action to occur immediately use <code>on: 'now'</code>. This will still trigger the same state updates to the invoked element, but will occur immediately.</p>
<p>
<div class="code" data-demo="true">
$('.follow.button')
.api({
action: 'follow user',
on: 'now'
})
;
</div>
<p>Keep in mind passing a new settings object will destroy the previous instance, and all its settings and events. If you want to preserve the previous instance, you can trigger a new request with the <code>query</code> behavior.</p>
<div class="code" data-demo="true">
// set-up API button with events
$('.follow.button')
.api({
action: 'follow user'
})
;
// do an immediate query
$('.follow.button')
.api('query')
;
</div>
</div>
<h2 class="ui dividing header">Setting-up Requests</h2>
<div class="no example">
<h4 class="ui header">Routing Data to URLs</h4>
<p>If your API URLs include templated variables they will be replaced during your request by one of four possible ways, listed in of inheritance.</p>
<p>All parameters used in a URL are encoded using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" target="_blank"><code>encodeURIComponent</code></a> by default, to prevent from malicious strings from affecting your query. To disable this feature you can set <a href="#settings"><code>encodeParameters: false</code></a>.
</div>
<div class="no routed example">
<h4 class="ui header">1. Automatically Routed URL Variables</h4>
<p>Some special values will be automatically replaced if specified in URL actions.</p>
<table class="ui definition table">
<thead>
<tr>
<th>Variable</th>
<th>Description</th>
<th>Available for</th>
</tr>
</thead>
<tbody>
<tr>
<td>text</td>
<td>current text value of element</td>
<td>All elements</td>
</tr>
<tr>
<td>value</td>
<td>current input value of element</td>
<td>Input elements</td>
</tr>
</tbody>
</table>
<div class="code" data-preview="true">
<div class="ui search icon input">
<i class="search icon"></i>
<input type="text" class="search">
</div>
</div>
<div class="evaluated code" data-type="javascript">
$.fn.api.settings.api.search = '/search/?query={value}';
$('.routed.example .search input')
.api({
action : 'search',
stateContext : '.ui.input'
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">2. URL Variables Specified in Data Attributes</h4>
<p>You can include URL values as HTML5 metadata attributes.</p>
<p>This is often the easiest way to include unique URL data for each triggering element. For example, many follow buttons will trigger the same endpoint, but each will have its own user id.</p>
<div class="ui ignored large warning message">
Only variables specified in your API's URL will be searched for in metadata.
</div>
<div class="code" data-type="html">
<div class="ui button" data-id="11">
Follow Sally
</div>
<div class="ui button" data-id="22">
Follow Jenny
</div>
</div>
<div class="code" data-type="javascript">
// requests different URLs for each button
$('.follow.button')
.api({
action: 'follow user'
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">3. Settings Specified in Javascript</h4>
<p>URL variables and GET/POST data can be specified at run-time in the Javascript object.</p>
<div class="code" data-type="javascript">
$('.follow.button')
.api({
action : 'follow user',
method : 'POST',
// Substituted into URL
urlData: {
id: 22
},
// passed via POST
data: {
name: 'Joe Henderson'
}
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">4. Settings Returned from beforeSend</h4>
<p>All run settings, not just URL data, can be adjusted in a special callback <code>beforeSend</code> which occurs before the API request is sent.</p>
<div class="ui info message">
An additional callback <code>beforeXHR</code> lets you modify the XHR object before sending. This is different than beforeSend which is used <b>to modify settings</b> before send.
</div>
<div class="code" data-type="javascript">
$('.follow.button')
.api({
action: 'follow user',
beforeSend: function(settings) {
settings.urlData = {
id: 22
};
return settings;
}
beforeXHR: function(xhr) {
// adjust XHR with additional headers
xhr.setRequestHeader ('Authorization', 'Basic XXXXXX');
return xhr;
}
})
;
</div>
</div>
<h2 class="ui dividing header">Adjusting Requests</h2>
<div class="no example">
<h4 class="ui header">Modifying XHR</h4>
<p>An additional callback <code>beforeXHR</code> lets you modify the XHR object before sending. This is useful for adjusting properties of the XHR request like modifying headers, before sending a request.</p>
<div class="code" data-type="javascript">
$('.follow.button')
.api({
action: 'follow user',
beforeXHR: function(xhr) {
// adjust XHR with additional headers
xhr.setRequestHeader ('Authorization', 'Basic XXXXXX');
return xhr;
}
})
;
</div>
</div>
<div class="no disabled example">
<h4 class="ui header">Disabling Requests</h4>
<p>As a convenience, API will automatically prevent requests from occurring on elements that are currently disabled.</p>
<div class="ui disabled button">Disabled</div>
<div class="evaluated code">
// this will never occur
$('.disabled.button')
.api({
action: 'follow user'
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">Cancelling Requests</h4>
<p>BeforeSend can also be used to check for special conditions for a request to be made. If the <code>beforeSend</code> callback returns false, the request will be cancelled.</p>
<div class="code" data-type="javascript" data-demo="true">
// set somewhere in your code
window.isLoggedIn = false;
$('.follow.button')
.api({
action: 'follow user',
beforeSend: function(settings) {
// cancel request
if(!isLoggedIn) {
$(this).state('flash text', 'Requires Login!');
return false;
}
}
})
;
</div>
</div>
<h2 class="ui dividing header">Passing Data</h2>
<div class="example">
<h4 class="ui header">1. Routed Form Data</h4>
<p>When you use the <code>serializeForm</code> setting or attach API events on a form, API will automatically include the closest form in data sent to the server.</p>
<p>Structured form data is beneficial over <a href="https://api.jquery.com/serialize/">jQuery's serialize</a> for several reasons:</p>
<ul class="ui large list">
<li><a href="https://github.com/macek/jquery-serialize-object" target="_blank">Serialize Object</a> correctly converts structured form names like <code>name="name[first]"</code> into nested object literals.</li>
<li>Structured form data can be modified in Javascript in <code>beforeSend</code>.</li>
<li>Form data will automatically be converted to their Javascript equivalents, for instance, checkboxes will be converted to <code>boolean</code> values.</li>
</ul>
<div class="ui ignored warning message">
Structured form data requires including <a href="https://github.com/macek/jquery-serialize-object" target="_blank">macek's serialize object.</a>
</div>
</div>
<div class="example">
<h4 class="ui header">Structured Data Example</h4>
<p>The following form shows some of the advantages of structured form data mentioned above.</p>
<form class="ui form">
<div class="two fields">
<div class="field">
<label>Name</label>
<div class="two fields">
<div class="field">
<input type="text" name="name[first]" placeholder="First Name">
</div>
<div class="field">
<input type="text" name="name[last]" placeholder="Last Name">
</div>
</div>
</div>
<div class="field">
<label>Gender</label>
<div class="ui selection dropdown">
<input type="hidden" name="gender">
<div class="default text">Gender</div>
<i class="dropdown icon"></i>
<div class="menu">
<div class="item" data-value="female">Female</div>
<div class="item" data-value="male">Male</div>
<div class="item" data-value="non-binary">Non-binary</div>
<div class="item" data-value="not-listed">None of the above</div>
</div>
</div>
</div>
</div>
<div class="two fields">
<div class="required field">
<label>Username</label>
<div class="ui icon input">
<input type="text" name="username" placeholder="Username">
<i class="user icon"></i>
</div>
</div>
<div class="required field">
<label>Password</label>
<div class="ui icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
</div>
<div class="ui submit button">Submit</div>
</form>
<div class="evaluated code" data-type="javascript">
$('form .submit.button')
.api({
action: 'create user',
serializeForm: true,
data: {
foo: 'baz'
},
beforeSend: function(settings) {
// form data is editable in before send
if(settings.data.username == '') {
settings.data.username = 'New User';
}
// open console to inspect object
console.log(settings.data);
return settings;
}
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">2. Data Routed in Javascript</h4>
<p>Server data can be specified directly when initializing an API requests.</p>
<div class="code" data-type="javascript">
$('.form .submit')
.api({
data: {
session: 22,
name: 'Baz'
}
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">3. Data Added in beforeSend</h4>
<p>POST or GET data can be specified using a special callback <code>beforeSend</code>, which can be used to retrieve data before sending a request.</p>
<div class="code" data-type="javascript">
$('.form .submit')
.api({
action: 'create user',
serializeForm: true,
// arbitrary POST/GET same across all requests
data: {
session: 22
},
// modify data PER element in callback
beforeSend: function(settings) {
// cancel request if no id
if(!$(this).data('id')) {
return false;
}
settings.data.userID = $(this).data('id');
return settings;
}
})
;
</div>
</div>
<h2 class="ui dividing header">Server Responses</h2>
<div class="no example">
<h4 class="ui header">Response Callbacks</h4>
<p>Successful responses from the server will trigger <code>onSuccess</code>, invalid results <code>onFailure</code>.<p>
<p><code>onError</code> will only trigger on <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XHR</a> errors, but not on invalid JSON responses.</p>
<p>You can use the <code>onResponse</code> callback to adjust the JSON response before being parsed against a success test.
<div class="code" data-type="javascript">
$('.follow.button')
.api({
onResponse: function(response) {
// make some adjustments to response
return response;
},
successTest: function(response) {
// test whether a JSON response is valid
return response.success || false;
},
onComplete: function(response) {
// always called after XHR complete
},
onSuccess: function(response) {
// valid response and response.success = true
},
onFailure: function(response) {
// request failed, or valid response but response.success = false
},
onError: function(errorMessage) {
// invalid response
},
onAbort: function(errorMessage) {
// navigated to a new page, CORS issue, or user canceled request
}
})
;
</div>
</div>
<div class="no example">
<h4 class="ui header">Determining JSON Success</h4>
<p>API has special success conditions for JSON responses. Instead of providing success and failure callbacks based on the HTTP response of the request, a request is considered successful only if the server's response tells you the action was successful. The response is passed to a validation test <code>successTest</code> which can be used to check the JSON for a valid response.</p>
<p>For example, you might expect all successful JSON responses to return a top level property signifying the success of the response:<p>
<div class="ui ignored info message">
You can use the <code>onResponse</code> callback to modify a server's response by returning a new translated response value before it is parsed by a success test.
</div>
<div class="code" data-type="json" data-title="Example Server Response">
{
"success": true,
"message": "We've retrieved your data from the server"
"data": {
// payload here
}
}
</div>
<p>You can specify a success test to check for this <code>success</code> value. This most likely will be set globally for all API requests.</p>
<div class="code" data-type="javascript">
$.fn.api.settings.successTest = function(response) {
if(response && response.success) {
return response.success;
}
return false;
};
</div>
</div>
<div class="no response example">
<h4 class="ui header">Modifying Response JSON</h4>
<p>Since version 2.0, API includes an <code>onResponse</code> callback which lets you adjust a server's response before a response is validated, allowing you to transform your response before other callbacks fire. This is useful for situations where an API response cannot be modified, but you need the response to conform with a required JSON structure.</p>
<div class="ui search">
<div class="ui left icon input">
<input class="prompt" type="text" placeholder="Search GitHub">
<i class="github icon"></i>
</div>
</div>
<div class="code" data-type="javascript">
$('.ui.search')
.search({
type : 'category',
minCharacters : 3,
apiSettings : {
url : '//api.github.com/search/repositories?q={query}',
onResponse : function(githubResponse) {
var
response = {
results : {}
}
;
if(!githubResponse || !githubResponse.items) {
return;
}
// translate GitHub API response to work with search
$.each(githubResponse.items, function(index, item) {
var
language = item.language || 'Unknown',
maxResults = 8
;
if(index >= maxResults) {
return false;
}
// create new language category
if(response.results[language] === undefined) {
response.results[language] = {
name : language,
results : []
};
}
// add result to category
response.results[language].results.push({
title : item.name,
description : item.description,
url : item.html_url
});
});
return response;
}
}
})
;
</div>
</div>
<h2 class="ui dividing header">Controlling State</h2>
<div class="no example">
<h4 class="ui header">UI State</h4>
<p>API will automatically add class names for <code>loading</code> and <code>error</code>. This will let you trigger different UI states automatically as an API call progresses.</p>
<p>If you need a different element than the triggering API element to receive state class names, you can specify a different selector using <code>settings.stateContext</code>.</p>
<p>Using <code>stateContext</code> allows you to easily do things like trigger a loading state on a form when a submit button is pressed.</p>
<h5 class="ui header">States Included in API Module</h5>
<table class="ui definition celled table">
<thead>
<tr>
<th>State</th>
<th class="six wide">Description</th>
<th>API event</th>
</tr>
</thead>
<tbody>
<tr>
<td>loading</td>
<td>Indicates a user needs to wait</td>
<td>XHR has initialized</td>
</tr>
<tr>
<td>error</td>
<td>Indicates an error has occurred</td>
<td>XHR Request returns error (does not trigger onAbort caused by page change, or if successTest fails). Stays visible for <code>settings.errorDuration</code></td>
</tr>
<tr>
<td>disabled</td>
<td>prevents API action</td>
<td>none</td>
</tr>
</tbody>
</table>
</div>
<div class="no example">
<h4 class="ui header">Text State</h4>
<p>Initializing an API action with the state module gives you more granular control over UI states, like setting an activated or de-activated state and the ability to adjust text values for each state:</p>
<!-- <p>
For additional examples of the possibilities available with state behaviors check the <a href="#">state module documentation</a>
</p> -->
<div class="code" data-demo="true">
$('.follow.button')
.api({
action: 'follow user'
})
.state({
onActivate: function() {
$(this).state('flash text');
},
text: {
inactive : 'Follow',
active : 'Followed',
deactivate : 'Unfollow',
flash : 'Added follower!'
}
})
;
</div>
<h5 class="ui header">States Included in State Module</h5>
<table class="ui definition celled table">
<thead>
<tr>
<th>State</th>
<th>Description</th>
<th>Occurs on</th>
</tr>
</thead>
<tbody>
<tr>
<td>inactive</td>
<td>Default state</td>
<td></td>
</tr>
<tr>
<td>active</td>
<td>Selected state</td>
<td>Toggled on succesful API request</td>
</tr>
<tr>
<td>activate</td>
<td>Explains activating action</td>
<td>On hover if inactive</td>
</tr>
<tr>
<td>deactivate</td>
<td>Explains deactivating action</td>
<td>On hover if active</td>
</tr>
<tr>
<td>hover</td>
<td>Explains interaction</td>
<td>On hover in all states, overrides activate/deactivate</td>
</tr>
<tr>
<td>disabled</td>
<td>Indicates element cannot be interacted</td>
<td>Triggered programatically. Blocks API requests.</td>
</tr>
<tr>
<td>flash</td>
<td>Text-only state used to display a temporary message</td>
<td>Triggered programatically</td>
</tr>
<tr>
<td>success</td>
<td>Indicates user action was a success</td>
<td>Triggered programatically</td>
</tr>
<tr>
<td>warning</td>
<td>Indicates there was an issue with a user action</td>
<td>Triggered programatically</td>
</tr>
</tbody>
</table>
</div>
<h2 class="ui dividing header">Advanced Use</h2>
<div class="no sync mocked example">
<h4 class="ui header">Fulfilling Responses</h4>
<p>Since version 2.0, API includes two new parameter <code>response</code> and <code>responseAsync</code> which allows you to specify a Javascript object or a function for returning an API response. (These were previously <code>mockResponse</code> and <code>mockResponseAsync</code>.)</p>
<div class="code" data-type="javascript" data-demo="true">
$('.sync.mocked .button')
.api({
response: {
success: true
}
})
.state({
text: {
inactive : 'Off',
active : 'On'
}
})
;
</div>
<div class="ui toggle button">
Off
</div>
</div>
<div class="no async mocked example">
<h4 class="ui header">Using Custom Backends</h4>
<p>Using <code>responseAsync</code> you can specify a function which can execute your API request. This allows for you to use custom backends or wrappers outside of <code>$.ajax</code> for integrating API requests.</p>
<div class="code" data-type="javascript" data-demo="true">
$('.async.mocked .button')
.api({
responseAsync: function(settings, callback) {
var response = {
success: true
};
// do any asynchronous task here
setTimeout(function() {
callback(response);
}, 500);
}
})
.state({
text: {
inactive : 'Off',
active : 'On'
}
})
;
</div>
<div class="ui toggle button">
Off
</div>
</div>
</div>
</div>
<div class="ui tab" data-tab="behaviors">
<h2 class="ui dividing header">Behavior</h2>
<p>All the following behaviors can be called using the syntax:</p>
<div class="code">
$('.your.element')
.api('behavior name', argumentOne, argumentTwo)
;
</div>
<table class="ui definition celled sortable table segment">
<thead>
<th>Behavior</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<td>query</td>
<td>Execute query using existing API settings</td>
</tr>
<tr>
<td>add url data(url, data)</td>
<td>Adds data to existing templated url and returns full url string</td>
</tr>
<tr>
<td>get request</td>
<td>Gets promise for current API request</td>
</tr>
<tr>
<td>abort</td>
<td>Aborts current API request</td>
</tr>
<tr>
<td>reset</td>
<td>Removes loading and error state from element</td>
</tr>
<tr>
<td>was cancelled</td>
<td>Returns whether last request was cancelled</td>
</tr>
<tr>
<td>was failure</td>
<td>Returns whether last request was failure</td>
</tr>
<tr>
<td>was successful</td>
<td>Returns whether last request was successful</td>
</tr>
<tr>
<td>was complete</td>
<td>Returns whether last request was completed</td>
</tr>
<tr>
<td>is disabled</td>
<td>Returns whether element is disabled</td>
</tr>
<tr>
<td>is mocked</td>
<td>Returns whether element response is mocked</td>
</tr>
<tr>
<td>is loading</td>
<td>Returns whether element is loading</td>
</tr>
<tr>
<td>set loading</td>
<td>Sets loading state to element</td>
</tr>
<tr>
<td>set error</td>
<td>Sets error state to element</td>
</tr>
<tr>
<td>remove loading</td>
<td>Removes loading state to element</td>
</tr>
<tr>
<td>remove error</td>
<td>Removes error state to element</td>
</tr>
<tr>
<td>get event</td>
<td>Gets event that API request will occur on</td>
</tr>
<tr>
<td>get url encoded value(value)</td>
<td>Returns <code>encodeURIComponent</code> value only if value passsed is not already encoded
</tr>
<tr>
<td>read cached response(url)</td>
<td>Reads a locally cached response for a URL</td>
</tr>
<tr>
<td>write cached response(url, response)</td>
<td>Writes a cached response for a URL</td>
</tr>
<tr>
<td>create cache</td>
<td>Creates new cache, removing all locally cached URLs</td>
</tr>
<tr>
<td>destroy</td>
<td>Removes API settings from the page and all events</td>
</tr>
</tbody>
</table>
</div>
<div class="ui tab" data-tab="settings">
<h2 class="ui dividing header">
API
</h2>
<h4 class="ui header">
AJAX
</h4>
<div class="ui info message">
You can pass in any standard <a href="http://api.jquery.com/jquery.ajax/">jQuery AJAX setting</a> like <code>timeout</code> or <code>contentType</code> to API's settings and it will be automatically passed to the request's AJAX call.
</div>
<h4 class="ui header">
API
</h4>
<table class="ui sortable celled definition table">
<thead>
<th class="three wide"></th>
<th class="three wide">Default</th>
<th>Description</th>
</thead>
<tbody>
<tr>
<td>on</td>
<td>auto</td>
<td>When API event should occur</td>
</tr>
<tr>
<td>cache</td>
<td>true</td>