-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_en.html
1286 lines (1089 loc) · 41.8 KB
/
index_en.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
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
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CandyJs js DOC</title>
<meta name="keywords" content="CandyJs MVC Framework Restful API">
<meta name="description" content="An object-oriented efficient node.js MVC and REST framework">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" >
<style>
blockquote {font-size: 14px;}
blockquote.bg-danger {
border-left-color: #cc3322;
}
blockquote.bg-info {
border-left-color: #1b809e;
}
footer {
background-color: #222;
color: #fff;
padding: 20px 0;
}
code {margin: 0 6px;}
</style>
</head>
<body>
<header>
<nav class="navbar navbar-inverse">
<div class="container">
<a target="_blank" class="navbar-brand" href="https://github.com/candyframework/candyjs">CandyJs</a>
</div>
</nav>
</header>
<div class="container" style="margin-top: 60px">
<div class="row">
<div class="col-md-9">
<h1>
An object-oriented efficient MVC and REST framework
</h1>
<blockquote class="bg-info">
The following content is translated by the machine
</blockquote>
<h1 class="page-header">Getting started</h1>
<p>Use the @candyjs/cli command to create a project</p>
<pre><code>
$ # install the command
$ npm install -g @candyjs/cli
$
$ # run the command
$ candyjs-cli
</code></pre>
<p>The command above will be presented with prompts for several optional features such as project name and TypeScript.and so on.</p>
<h1 class="page-header" id="firstrun"><b>Run the program for the first time</b></h1>
<p>After run the command, a simple application will be create</p>
<p>
<pre><code>
PROJECT_NAME
|
|- index.js
|
|- app
| |
| |-- controllers
| |
| |-- index
| | |
| | |-- IndexController.js
| |
| -- views
| |
| |-- index
| | |
| | |-- index.html
</code></pre>
</p>
<p>Go to the application directory to start the program</p>
<p><pre><code>$ npm install && npm run start</code></pre></p>
<p>Access</p>
<p><pre><code><a href="http://localhost:2333" target="_blank">http://localhost:2333</a></code></pre></p>
<h1 class="page-header" id="appstruct">Application structure</h1>
<h4><b>An application directory structure is amy as follows</b></h4>
<p>
<pre><code>
PROJECT_NAME
|
|- index.js
|
|- node_modules
|
|- public
|
|- app
| |
| |-- controllers
| |
| |-- user
| | |
| | |-- IndexController.js
| | |-- OtherController.js
| |
| |-- goods
| | |
| | |-- IndexController.js
| | |-- OtherController.js
| |
| -- views
| |
| |-- user
| | |
| | |-- index.html
| | |-- other.html
| |
| |-- goods
| | |
| | |-- index.html
| | |-- other.html
| |
| -- runtime
|
</pre></code>
</p>
<h4><b>Entry script<code>index.js</code></b></h4>
<p>
The entry script is the first loop in the application startup process.
There is only one entry script that contains the startup code that will listen to the client's connection
</p>
<p>
The entry script basically does the following
<ul>
<li>Load the application configuration</li>
<li>Start the application</li>
<li>Register all the required components</li>
</ul>
</p>
<p>
<pre><code>
var CandyJs = require('candyjs');
var App = require('candyjs/web/Application');
new CandyJs(new App({
'id': 1,
'debug': true,
// application path
'appPath': __dirname + '/app',
// register modules
'modules': {
'bbs': 'app/modules/bbs'
},
// log setting
'log': {
'targets': {
'file': {
'classPath': 'candy/log/file/Log'
}
}
}
})).listen(2333, function(){
console.log('listen on 2333');
});
</pre></code>
</p>
<h4><b>Application</b></h4>
<p>
Applications are objects that govern the overall structure and lifecycle of<code>CandyJs</code>application systems.
<code>CandyJs</code>has two kinds of Application:<code>Web Application</code> and <code>Rest Application</code>
</p>
<h4><b>Application properties</b></h4>
<p>
Various parameters can be introduced in the entry file.
These parameters will eventually be assigned to the application instance object
</p>
<h6><b>Required properties</b></h6>
<ul>
<li>
<p><code>candy/web/Application.id</code>This property is used to identify the only application</p>
</li>
<li>
<p><code>candy/web/Application.appPath</code>This property used to specified application directory</p>
</li>
</ul>
<h6><b>Important attributes</b></h6>
<ul>
<li>
<p><code>candy/web/Application.routesMap</code>Used to define the routing handler</p>
<p>
<pre><code>
'account': {
'classPath': 'app/controllers/user/IndexController',
'property': 'value'
}
</code></pre>
</p>
</li>
<li>
<p><code>candy/web/Application.modules</code>To register application module</p>
<p>
<pre><code>
// register a bbs module
'modules': {
'bbs': 'app/modules/bbs'
}
</code></pre>
</p>
</li>
<li>
<p><code>candy/web/Application.encoding</code>Project encoding</p>
</li>
<li>
<p><code>candy/web/Application.debug</code>Whether debugging is on</p>
</li>
</ul>
<h4><b>Custom properties</b></h4>
<p>Other parameters passed in the entry file are passed to the application as a custom parameter</p>
<h1 class="page-header" id="controller"><b>Application controller</b></h1>
<p>The controller is part of the<code>MVC</code>schema that inherits the object of<code>candy/core/AbstractController</code>class responsible for handling the request and generating the response</p>
<h4><b>Action</b></h4>
<p>
The controller consists of<code>actions</code>that is the most basic unit for executing the end user's request.
A controller has and only one entry action is called<code>run</code>
</p>
<p>
<pre><code>
'use strict';
const Controller = require('candyjs/web/Controller');
class IndexController extends Controller {
// entry action
run(req, res) {
res.end('hello');
}
}
module.exports = IndexController;
</pre></code>
</p>
<h1 class="page-header" id="filter"><b>ActionAspect</b></h1>
<p>ActionAspect is a special behavior class for filter user request.</p>
<p><code>ActionAspect</code>has two useful methods:<code>beforeAction(actionEvent)</code>and<code>afterAction(actionEvent)</code></p>
<h4><b>How to use</b></h4>
<h6><b>1. write a aspect program</b></h6>
<p>In order to use aspects, you must first write the aspect class,which is the subclass of<code>candyjs/core/ActionAspect</code></p>
<pre><code>
// app/filters/Cors.js
const ActionAspect = require('candyjs/core/ActionAspect');
module.exports = class Cors extends ActionAspect {
constructor() {
super();
this.cors = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS',
'Access-Control-Allow-Headers': '',
'Access-Control-Max-Age': 86400,
'Access-Control-Allow-Credentials': true
};
}
/**
* add http header
*/
beforeAction(actionEvent) {
let request = actionEvent.request;
let response = actionEvent.response;
let headers = this.generateHeaders(request);
for(let k in headers) {
response.setHeader(k, headers[k]);
}
if('OPTIONS' === request.method) {
actionEvent.valid = false;
response.writeHead(200, 'OK');
response.write('');
response.end();
}
}
generateHeaders(request) {
let ret = {};
// oirigin
if(undefined !== request.headers['origin'] && undefined !== this.cors['Access-Control-Allow-Origin']) {
if(this.cors['Access-Control-Allow-Origin'].indexOf(request.headers['origin']) >= 0) {
ret['Access-Control-Allow-Origin'] = request.headers['origin'];
}
// allow origin=* and allow credentials can not appear at the same time
if('*' === this.cors['Access-Control-Allow-Origin']) {
if(this.cors['Access-Control-Allow-Credentials']) {
throw new Error('Allowing credentials for wildcard origins is insecure');
} else {
ret['Access-Control-Allow-Origin'] = '*';
}
}
}
if(undefined !== request.headers['access-control-request-method']) {
ret['Access-Control-Allow-Methods'] = this.cors['Access-Control-Allow-Methods'];
}
if(undefined !== this.cors['Access-Control-Allow-Headers']) {
ret['Access-Control-Allow-Headers'] = this.cors['Access-Control-Allow-Headers'];
}
if(undefined !== this.cors['Access-Control-Allow-Credentials']) {
ret['Access-Control-Allow-Credentials'] = this.cors['Access-Control-Allow-Credentials'] ? 'true' : 'false';
}
if('OPTIONS' === request.method && undefined !== this.cors['Access-Control-Max-Age']) {
ret['Access-Control-Max-Age'] = this.cors['Access-Control-Max-Age'];
}
return ret;
}
}
</pre></code>
<h6><b>2. work with aspect</b></h6>
<p>It is simple to use your accept class, just add a<code>behaviors()</code>method to your controller</p>
<pre><code>
class IndexController extends Controller {
// the value 'mycors' valus is an alias of your Aspect class, you can rename it to any
behaviors() {
return [
['mycors', 'app/filters/Cors']
];
}
run() {
// the behaviors() method will execute first
}
}
</pre></code>
<h1 class="page-header"><b>Filters</b></h1>
<p>A filter is a class that implements the <code>core/IFinter</code> interface,or any class with<code>doFilter (req, res, chain)</code>function can also considered to be a filter</p>
<p>The usage of filter and acpect are similar, except that the filter configuration is returned by the<code>filters()</code>function</p>
<pre><code>
class IndexController extends Controller {
// 'app/filters/MyFilter' is the class path of the filter
filters() {
return [
'app/filters/MyFilter'
];
}
run() {}
}
// app/filters/MyFilter
module.exports = class MyFilter {
doFilter(req, res, filterChain) {
// todo something
// manually execute the next filter
filterChain.doFilter(req, res);
}
}
</pre></code>
<blockquote class="bg-info">
<p>Both aspect and filter can filter user requests before the controller executes, the filter is more user-friendly for asynchronous operations</p>
</blockquote>
<h1 class="page-header" id="routers">Routers</h1>
<p>In General, a router corresponds to a controller, there are two kinds of routers</p>
<ol>
<li><p><code>route_prefix[/controllerId]</code></p></li>
<li><p><code>moduleId[/controllerId]</code></p></li>
</ol>
<blockquote class="bg-info">
The part of<code>[/controllerId]</code>can be omitted, and its default value is<code>index</code>, so the default controller is<code>IndexControlelr</code>
</blockquote>
<ul>
<li>
<p>when visit <a>http://localhost/</a></p>
<p><code>app/controllers/index/IndexControlelr</code>will be created, this is the default home page controller</p>
</li>
<li>
<p>when visit <a>http://localhost/user</a></p>
<p><code>user</code>module will be searched first</p>
<p>if found, then<code>app/modules/user/controllers/IndexController</code>will be created</p>
<p>if not found,then<code>app/controllers/user/IndexController</code>will be created</p>
</li>
<li>
<p>when visit <a>http://localhost/user/profile</a></p>
<p><code>user</code>module will be searched first</p>
<p>if found, then<code>app/modules/user/controllers/ProfileController</code>will be created</p>
<p>if not, then<code>app/controllers/user/ProfileController</code>will be created</p>
</li>
<li>
<p>when visit <a>http://localhost/user/profile/settings</a></p>
<p><code>user</code>module will be searched first</p>
<p>if found then<code>app/modules/user/controllers/SettingsController</code>will be created, the 'profile' part will be ignored</p>
<p>if not, then<code>app/controllers/user/profile/SettingsController</code>will be created</p>
</li>
</ul>
<blockquote class="bg-info">
<p>Controller search order<code>module controller --> common controller</code></p>
</blockquote>
<h1 class="page-header" id="model"><b>Model</b></h1>
<p>The model is part of the<code>MVC</code>pattern that represents the object of the business data</p>
<blockquote class="bg-info">
<p><a target="_blank" href="https://github.com/candyframework/candyjs-examples/tree/master/model">see here for detail</a></p>
</blockquote>
<h1 class="page-header" id="view"><b>视图</b></h1>
<p>视图是<code>MVC</code>模式中的一部分 它用于给终端用户展示页面</p>
<h4><b>模板引擎</b></h4>
<blockquote class="bg-info">
<code>CandyJs</code>提供了<code>@candyjs/template-hbs</code>来负责模板渲染,<a target="_blank" href="https://github.com/candyframework/candyjs-template-hbs">查看详情</a>
</blockquote>
<h4><b>其他方式使用模板引擎</b></h4>
<p>得益于<code>CandyJs</code>灵活的架构设计,使得模板引擎使用非常便捷,这里有如下几种方式:</p>
<ul>
<li>全局配置方式</li>
<li>局部注入方式</li>
<li>嵌入式</li>
</ul>
<p>下面将使用<code>Handlebars</code>对以上方式进行逐个讲解</p>
<h6><b>全局配置方式</b></h6>
<p>
<pre><code>
// 全局配置方式是使用 candyjs 的别名系统实现的
// 这里的代码可以从源代码 examples 目录中找到
// 1. 在 app/libs 目录中建立一个模板引擎文件 CandyTemplate.js
const fs = require('fs');
const Handlebars = require('handlebars');
// 加载系统视图类
const View = require('candyjs/web/View');
class CandyTemplate extends View {
constructor(context) {
super(context);
this.handlebars = Handlebars.create();
}
// 模板引擎必须实现这个方法,因为它是渲染模板的入口
renderFile(file, parameters) {
fs.readFile(file, 'UTF-8', (err, template) => {
let compiled = this.handlebars.compile(template);
this.context.response.end( compiled(parameters) );
});
}
}
module.exports = CandyTemplate;
// 2. 经过第 1 步,我们的模板引擎就开发完了,是不是很简单
// 接下来在入口注册我们编写的模板引擎
const App = require('candyjs/web/Application');
const app = new App({
'id': 'template_test',
// 配置模板引擎
'defaultView': 'app/libs/CandyTemplate',
'appPath': __dirname + '/app'
});
new CandyJs(app).listen(2333, function(){
console.log('listen on 2333');
});
// 3. 准备模板 html
<html>
<body>
<ul>
{{#each list}}
<li><a href="/user?uid={{ id }}">{{ name }}</a></li>
{{/each}}
</ul>
</body>
</html>
// 4. 在控制器中使用模板引擎渲染页面
const Controller = require('candyjs/web/Controller');
const User = require('somepath/models/User');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
// 这里 data 是一个用户数组 [{id: xxx, name: xxx}]
let data = await user.getUserList();
// 可以获取到模板引擎实例
// 具体使用方式请参考 handlebars 模板引擎官方文档
// const handlebars = this.getView().handlebars;
// handlebars.todo
// 这里的 render 将使用我们制定的模板引擎渲染页面
this.render('index', {
list: data
});
}
}
</code></pre>
</p>
<h6><b>局部注入方式</b></h6>
<p>
<pre><code>
// 1. 局部注入方式第 1 步也需要编写我们的模板引擎,参考全局配置方式
// 2. 在控制器中动态注入模板引擎
const Controller = require('candyjs/web/Controller');
const User = require('somepath/models/User');
const CandyTemplate = require('somepath/CandyTemplate');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
let data = await user.getUserList();
// 动态注入模板引擎
this.setView(new CandyTemplate(this.context));
this.render('index', {
list: data
});
}
}
module.exports = IndexController;
</code></pre>
</p>
<h6><b>嵌入式</b></h6>
<p>
<pre><code>
// 这种方式比较灵活,不需要编写模板引擎
const Controller = require('candyjs/web/Controller');
const Handlebars = require('handlebars');
const User = require('somepath/models/User');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
let data = await user.getUserList();
this.getView().getTemplateContent('index', (err, str) => {
// 直接使用模板引擎对内容进行编译并输出
let compiled = Handlebars.compile(str);
res.end( compiled({ list: data }) );
});
}
}
module.exports = IndexController;
</code></pre>
</p>
<h4><b>Controller level view API</b></h4>
<p>
If the user's controller inherits from the<code>candy/web/Controller</code>
then can use the<code>getView()</code>method in the controller to get the view class instance
</p>
<p>The view class provides the following API for user to use</p>
<ul>
<li><code>findViewFile(view)</code>Used to get absolute path of a view file</li>
<li><code>getTemplateContent(view, callback)</code>Used to read the content of a view file</li>
</ul>
<p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
run(req, res) {
this.getView().getTemplateContent('index', (err, str) => {
res.end(str);
});
}
}
module.exports = IndexController;
</code></pre>
</p>
<h1 class="page-header" id="module"><b>Module</b></h1>
<p>
Module is independent software unit.
It consists of<code>Model View Controller</code>and other necessary components
</p>
<blockquote class="bg-info">
Note that unlike the common project directory, the controllers and views in the module do not have a subdirectory
</blockquote>
<h4><b>Create a module</b></h4>
<p>In the<code>modules</code>directory create a separate directory eg. bbs</p>
<p>
<pre><code>
modules
|
|-- bbs
| |
| |-- controllers
| | |
| | |-- IndexController.js
| |
| |-- views
| | |
| | |-- index.html
| |
| |-- other directory
</code></pre>
</p>
<h4><b>Register the module</b></h4>
<p>The module created can not be recognized by the system, we need to manually register</p>
<p>
<pre><code>
var CandyJs = require('candyjs');
var App = require('candyjs/web/Application');
new CandyJs(new App({
...
// register module bbs
'modules': {
'bbs': 'app/modules/bbs'
},
...
})).listen(2333, function(){
console.log('listen on 2333');
});
</code></pre>
</p>
<h1 class="page-header" id="component"><b>Component & Behavior</b></h1>
<h4><b>Component</b></h4>
<p>Component is the base class of<code>Behavior and Event</code></p>
<p>Components are instances of<code>candy/core/AbstractController</code>, or an extended class</p>
<p>Behavior classes are typically used in conjunction with component classes</p>
<h4><b>Behavior</b></h4>
<p>Behavior is instances of<code>candy/core/Behavior</code>, or an extended class</p>
<p>A behavior class can be used to enhance its functionality without changing the original component code</p>
<p>When a behavior is attached to a component, it will inject its methods and properties into the component and then access them as if they were to access the component's own methods and properties</p>
<p>The behavior class also can listen to the component's events and respond</p>
<h4><b>Event</b></h4>
<p><code>CandyJs</code>implements an observer pattern</p>
<p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
constructor(context) {
super(context);
this.on('myevent', function() {
console.log('myevent fired');
});
}
run(req, res) {
this.trigger('myevent');
res.end('hello');
}
}
module.exports = IndexController;
</code></pre>
</p>
<h4><b>Use behavior</b></h4>
<h6><b>Define behavior</b></h6>
<p>Create a class by inheriting<code>candy/core/Behavior</code>or its subclasses</p>
<p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Behavior = Candy.include('candy/core/Behavior');
// 行为类
class MyBehavior extends Behavior {
constructor() {
super();
}
// 监听控制器的 customEvent 事件
// 由于一个事件可以有多个处理程序 为保证顺序 这里必须使用数组
// 格式为 [行为名, 行为处理器]
events() {
return [
['customEvent', (e) => {
e.result = 'data processed by behavior';
}],
['customEvent2', (e) => {
e.result += '--process2';
}]
];
}
}
module.exports = MyBehavior;
</code></pre>
</p>
<p>The above code defines the behavior class<code>MyBehavior</code>and provides two properties<code>prop1 prop2</code>and a method for the component to attach the behavior<code>myFun()</code></p>
<h6><b>Attach behavior to component</b></h6>
<p>You can attach a behavior to a component either statically or dynamically</p>
<p>To attach a behavior statically, override the<code>behaviors()</code>method of the component class to which the behavior is being attached</p>
<p>The<code>behaviors()</code>method should return a list of behavior configurations</p>
<p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
// 重写方法
behaviors() {
return [
['myBehavior', new MyBehavior()]
];
}
run(req, res) {
let data = {result: ''};
this.trigger('customEvent', data);
// 卸载行为
this.detachBehavior('myBehavior');
return data.result;
}
}
module.exports = IndexController;
</code></pre>
</p>
<p>To attach a behavior dynamically, call the<code>attachBehavior()</code>method of the component to which the behavior is being attached</p>
<p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
constructor(context) {
super(context);
// 动态附加行为 行为里面会监听 customEvent 事件
this.attachBehavior('myBehavior', new MyBehavior());
}
run(req, res) {
let data = {result: ''};
this.trigger('customEvent', data);
this.trigger('customEvent2', data);
this.detachBehavior('myBehavior');
return data.result;
}
}
module.exports = IndexController;
</code></pre>
</p>
<h1 class="page-header" id="midware"><b>Middleware</b></h1>
<p>The middleware is the first part of the request to process the request and do the filtering and call the next middleware</p>
<blockquote class="bg-info">
<code>CandyJs</code>temporarily only provides a middleware for handling static resources
</blockquote>
<h1 class="page-header" id="static"><b>Static resource</b></h1>
<p>
<code>CandyJs</code>defaults to non-processing of static resources that require the use of middleware
</p>
<p>
<pre><code>
var CandyJs = require('candyjs');
var Candy = require('candyjs/Candy');
var App = require('candyjs/web/Application');
var Hook = require('candyjs/core/Hook');
var R = require('candyjs/midwares/Resource');
// serve the public dir as static resources
// before 4.20.0
// Hook.addHook(R.serve(__dirname + '/public'));
// after 4.20.0, add multiple dir support
Hook.addHook(new R(__dirname + '/public').serve());
new CandyJs(new App({
...
})).listen(2333, function(){
console.log('listen on 2333');
});
// in view file, we can use static resource like this: /public/js/lib.js
<script src="/js/lib.js"></script>
</code></pre>
</p>
<h1 class="page-header" id="url"><b>URI & URL</b></h1>
<p>
<code>candy/web/URI and candy/web/URL</code>classes provide methods for uri and url operations
</p>
<h4><b>candy/web/URI</b></h4>
<ul>
<li><code>parseUrl()</code>Used for parse url</li>
</ul>
<p>
<pre><code>
var URI = Candy.include('candy/web/URI');
var uri = new URI();
/*
{
source: 'http://xxx.com:8080/abc?q=1#anchor',
scheme: 'http',
user: undefined,
password: undefined,
host: 'xxx.com',
port: '8080',
path: '/abc',
query: 'q=1',
fragment: 'anchor'
}
*/
uri.parseUrl('http://xxx.com:8080/abc?q=1#anchor');
</code></pre>
</p>
<h4><b>candy/web/URL</b></h4>
<ul>
<li><code>getReferer()</code>Used to get the referer url</li>
<li><code>getHostInfo()</code>Used to get the host section of URI</li>
<li><code>getCurrent()</code>Used to get the current URL</li>
<li><code>to(url[, params = null])</code>Used to create a url</li>
</ul>
<p>
<pre><code>
var URL = Candy.include('candy/web/URL');
var url = new URL(req);
// return scheme://host/index/index
url.to('index/index');
// return scheme://host/index/index?id=1#anchor
url.to('index/index', {id: 1, '#': 'anchor'})
</code></pre>
</p>
<h1 class="page-header" id="reqres"><b>Request and Response</b></h1>
<p>
<code>CandyJs</code>provides classes<code>candy/http/Request</code>and<code>candy/http/Response</code>that handle requests and responses
</p>
<h4><b>HTTP Request</b></h4>
<p>Used to handle http requests</p>
<p>
<code>candy/http/Request</code>class provides a set of instances and static methods to manipulate the required data
</p>
<ul>
<li><code>getQueryString(param)</code>Instance method get the request parameter</li>
<li><code>getParameter(param)</code>Instance method get the POST request parameter</li>
<li><code>getCookie(name)</code>Instance method get cookies</li>
<li><code>getHeaders()</code>Get http headers</li>
</ul>
<blockquote class="bg-danger">
In the use of<code>getParameter()</code>to obtain the POST parameter temporarily need to rely on third-party analysis of the body of the middleware will otherwise back to the null
</blockquote>
<p>
<pre><code>
var Request = Candy.include('candy/http/Request');
var request = new Request(req);
var id = request.getQueryString('id');
...
</code></pre>
</p>
<h4><b>HTTP Response</b></h4>
<p>Outputs a response message to the client</p>
<p>
<code>candy/http/Response</code>class provides a set of instances and static methods to manipulate the response data
</p>
<ul>
<li><code>setStatusCode(value[, text])</code>Set the http status code</li>
<li><code>setHeader(name, value)</code>Set the header</li>
<li><code>setContent(content)</code>Set the entity content</li>
<li><code>setCookie(name, value[, options])</code>Set a cookie</li>
<li><code>send([content])</code>Send an HTTP response to the client</li>
<li><code>redirect(url[, statusCode = 302])</code>Page redirection</li>
</ul>
<h6><b>Use the Response to output data</b></h6>
<p>
<pre><code>
var Response = Candy.include('candy/http/Response');
var response = new Response(res);
response.setContent('some data from server');
response.send();
</code></pre>
</p>
<h6><b>Use the Response to redirection</b></h6>
<p>
<pre><code>
var Response = Candy.include('candy/http/Response');
var response = new Response(res);
response.redirect('http://foo.com');
</code></pre>
</p>
<h1 class="page-header" id="helper"><b>Assistant class</b></h1>
<p>The assistant class encapsulates some common operations</p>
<h4><b>File Assistant class<code>FileHelper</code></b></h4>
<ul>
<li><code>getDirname(dir)</code></li>
<li><code>normalizePath(path[, directorySeparator = '/'])</code></li>
<li><code>createDirectory(dir[, mode = 0o777[, callback = null]])</code></li>
<li><code>createDirectorySync(dir[, mode = 0o777])</code></li>
</ul>
<h4><b>String helper class<code>StringHelper</code></b></h4>
<ul>
<li><code>nIndexOf(str, find, n)</code>Find the position where a string appears at the Nth occurrence in another string</li>
<li><code>trimChar(str, character)</code></li>
<li><code>lTrimChar(str, character)</code></li>