-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1098 lines (827 loc) · 170 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
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">
<title>M & D</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="June & July">
<meta property="og:type" content="website">
<meta property="og:title" content="M & D">
<meta property="og:url" content="https://dontcallmilanac.github.io/index.html">
<meta property="og:site_name" content="M & D">
<meta property="og:description" content="June & July">
<meta property="og:locale" content="en_US">
<meta property="article:author" content="qibw">
<meta property="article:tag" content="fe,web">
<meta name="twitter:card" content="summary">
<link rel="alternate" href="/atom.xml" title="M & D" type="application/atom+xml">
<link rel="icon" href="/favicon.png">
<link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/css/style.css">
<meta name="generator" content="Hexo 5.4.0"></head>
<body>
<div id="container">
<div id="wrap">
<header id="header">
<div id="banner"></div>
<div id="header-outer" class="outer">
<div id="header-title" class="inner">
<h1 id="logo-wrap">
<a href="/" id="logo">M & D</a>
</h1>
</div>
<div id="header-inner" class="inner">
<nav id="main-nav">
<a id="main-nav-toggle" class="nav-icon"></a>
<a class="main-nav-link" href="/">Home</a>
<a class="main-nav-link" href="/archives">Archives</a>
</nav>
<nav id="sub-nav">
<a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
<a id="nav-search-btn" class="nav-icon" title="Search"></a>
</nav>
<div id="search-form-wrap">
<form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"></button><input type="hidden" name="sitesearch" value="https://dontcallmilanac.github.io"></form>
</div>
</div>
</div>
</header>
<div class="outer">
<section id="main">
<article id="post-eventloop" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2021/04/17/eventloop/" class="article-date">
<time datetime="2021-04-17T09:47:48.000Z" itemprop="datePublished">2021-04-17</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2021/04/17/eventloop/">终于来了,事件循环!</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h2 id="什么是事件循环?"><a href="#什么是事件循环?" class="headerlink" title="什么是事件循环?"></a>什么是事件循环?</h2><p>这就要牵扯很多概念了。首先,拆解来看。</p>
<ul>
<li>事件:应该都很熟悉了,之前写过发布订阅提到了事件机制。我的理解是,js 作为一门脚本语言,为了完成我们程序员给它指定的各种任务,就必须要有个机制来跟我们交互。知道何时应该接受输入,何时做出计算处理,然后何时给出处理结果并予以输出反馈。而事件机制就很好地完成了这些。与此同时,js 的运行环境(这里当然暂时指浏览器和 node,deno 再发展发展,哈哈)不仅完成了上述的任务,同时还实现了许多别的事情。浏览器的终极目标是渲染网页,让用户能够看到网页所展示的信息;而 node 没有图形界面,但能够完成各种 IO 操作,也是程序员的好帮手。</li>
<li>循环:字面意思看来,应该也是一种策略或是机制。即重复这个事件处理的过程,通过一个个的事件处理,并循环往复,最终完成它所有的任务,实现它的价值(最终应该也是不准确的,可以理解为一段时间内)。</li>
</ul>
<h2 id="浏览器的事件循环"><a href="#浏览器的事件循环" class="headerlink" title="浏览器的事件循环"></a>浏览器的事件循环</h2><ul>
<li>进程和线程<br>首先,说说进程和线程。</li>
<li>node 的事件循环</li>
<li>微任务</li>
<li>宏任务</li>
<li>浏览器和 node 的差别</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2021/04/17/eventloop/" data-id="ckqond46m0000bcre4fhz46br" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/eventloop/" rel="tag">eventloop</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF/" rel="tag">事件循环</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%AE%8F%E4%BB%BB%E5%8A%A1/" rel="tag">宏任务</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%BE%AE%E4%BB%BB%E5%8A%A1/" rel="tag">微任务</a></li></ul>
</footer>
</div>
</article>
<article id="post-debouce-throttle" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2021/03/20/debouce-throttle/" class="article-date">
<time datetime="2021-03-20T07:15:18.000Z" itemprop="datePublished">2021-03-20</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2021/03/20/debouce-throttle/">来了来了,防抖节流!</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h2 id="老生常谈,防抖节流"><a href="#老生常谈,防抖节流" class="headerlink" title="老生常谈,防抖节流"></a>老生常谈,防抖节流</h2><ul>
<li>老样子,首先剖析概念</li>
<li>先看防抖:英语 debounce。先看 bounce,反弹、弹跳的意思。那加个 de 前缀,学过点英语就知道,表否定。所以 debounce 是让它别反弹、弹跳,综合理解,即我们常说的去抖动,防抖。</li>
<li>那防抖跟我们编程有啥关系?在网页中,有一些事件是会触发非常频繁的,比如鼠标移动(onmousemove),键盘输入(onkeypress 如果你打字速度够快的话),还有窗口大小调整时的 onresize 等等。</li>
<li>发现了吗,有点联系了,频繁和弹跳,我们理解为同义。想象一个弹力球扔在地上,它一定会反弹起来数次,最终停在地上。就像上述的那些事件一样,触发太频繁,但最终会稳定。这里事件的稳定我们认为就是一段时间内没有触发。</li>
<li>所以对于不稳定的事件,我们不需要也不太容易知道它如此频繁的每一次的不同状态。我们要做的是,等它稳定了,不抖动了,不弹跳了,再去做一些处理。这样能够有效节约资源,且不会丢失关键的信息和逻辑。类比一下更通俗的例子,电梯和公交车,门开了,都是不停的上人,门就不能关,必须等没人上了,准确说是一段时间内没人上了,才能关门,所以这就是防抖。</li>
<li>具体到代码,怎么实现呢?这就用到了鼎鼎大名的闭包。一句话即函数外用到了函数内的变量。先来最简版:</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> test1 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test1"</span>, e, <span class="built_in">this</span>); <span class="comment">// 普通测试函数,打印事件e和this,就别用箭头函数了</span></span><br><span class="line">};</span><br><span class="line"><span class="keyword">let</span> timer; <span class="comment">// 借助了全局变量</span></span><br><span class="line"><span class="keyword">const</span> test2 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="comment">// console.log(timer); // 可以看看每次的timer是什么</span></span><br><span class="line"> <span class="keyword">if</span> (timer) {</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timer); <span class="comment">// 如果没有到1000ms,就清掉计时器</span></span><br><span class="line"> }</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> <span class="comment">// 不管有没有清理计时器,都要开始计时,即延时执行函数</span></span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test2"</span>, e, <span class="built_in">this</span>);</span><br><span class="line"> }, <span class="number">1000</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> target = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"body"</span>)[<span class="number">0</span>];</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test1);</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test2);</span><br></pre></td></tr></table></figure>
<ul>
<li>可以看到效果就是,test1 一直触发,不做任何限制,即我们所说的抖动。</li>
<li>而 test2 是人为地去掉了所有抖动的触发,即忽略掉了抖动中,也就是限定时间内的频繁执行,我们清理了定时器,则自然回调不会被执行。而如果过了限定的时间,则定时器会自动触发一次之前缓存的函数。</li>
<li>有个问题,这里例子不通用,还用到了全局变量,那如果想复用这个操作咋办?简单,闭包!</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 封装一个包裹函数,返回去掉了抖动的函数</span></span><br><span class="line"><span class="keyword">const</span> debounce = <span class="function">(<span class="params">func, wait</span>) =></span> {</span><br><span class="line"> <span class="keyword">let</span> timer; <span class="comment">// 从原来的全局变量变成了闭包,是不是闭包理解又深刻了!</span></span><br><span class="line"> <span class="comment">// 注意这里不能用箭头函数</span></span><br><span class="line"> <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="comment">// console.log(timer); // 可以看看每次的timer是什么</span></span><br><span class="line"> <span class="keyword">if</span> (timer) {</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timer);</span><br><span class="line"> }</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>); <span class="comment">//apply,call,bind的区别是什么,哈哈哈引申狂魔</span></span><br><span class="line"> }, wait);</span><br><span class="line"> };</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test1 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test1"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test2 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test2"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> target = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"body"</span>)[<span class="number">0</span>];</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test1);</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, debounce(test2, <span class="number">1000</span>));</span><br></pre></td></tr></table></figure>
<ul>
<li>上述例子实现了复用防抖逻辑,还专门处理了 this,但还有个问题,如果这个事件就是一直触发,不停咋办?那我们封装的防抖就永远不能执行,如果想让它至少先来执行一次,怎么改改?</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 封装一个包裹函数,返回去掉了抖动的函数</span></span><br><span class="line"><span class="keyword">const</span> debounce = <span class="function">(<span class="params">func, wait, immediate</span>) =></span> {</span><br><span class="line"> <span class="keyword">let</span> timer; <span class="comment">// 从原来的全局变量变成了闭包,是不是闭包理解又深刻了!</span></span><br><span class="line"> <span class="keyword">let</span> callNow;</span><br><span class="line"> <span class="comment">// 注意这里不能用箭头函数</span></span><br><span class="line"> <span class="keyword">const</span> debounced = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="comment">// console.log(timer); // 可以看看每次的timer是什么</span></span><br><span class="line"> <span class="keyword">if</span> (timer) {</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timer);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (immediate) {</span><br><span class="line"> <span class="comment">// 若需要立即执行,记录一个状态</span></span><br><span class="line"> callNow = !timer;</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> timer = <span class="literal">null</span>; <span class="comment">// 改变了timer,下次再执行时就又开始一轮新的循环,会立即执行</span></span><br><span class="line"> }, wait);</span><br><span class="line"> <span class="keyword">if</span> (callNow) func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>); <span class="comment">//apply,call,bind的区别是什么,哈哈哈引申狂魔</span></span><br><span class="line"> }, wait);</span><br><span class="line"> }</span><br><span class="line"> };</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test1 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test1"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test2 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test2"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> target = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"body"</span>)[<span class="number">0</span>];</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test1);</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, debounce(test2, <span class="number">1000</span>, <span class="literal">true</span>));</span><br></pre></td></tr></table></figure>
<ul>
<li>好了,防抖差不多了。那啥是节流呢?throttle 意为节流阀,油门等,顾名思义,就是限制流量,限制事件触发的次数。</li>
<li>之所以把它俩放一起写,肯定有原因的。比较相似:防抖是一堆事件只执行一次(最后一次或第一次)。而节流是一堆事件中,在固定时间内最多执行一次,也可能不执行。也可以理解为,在固定时间内的防抖,仔细想想,是不是这个道理?</li>
<li>节流也是先来最简版实现吧,其实就在防抖基础上改两行!</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 封装一个包裹函数,返回节流后的函数</span></span><br><span class="line"><span class="keyword">const</span> throttle = <span class="function">(<span class="params">func, wait</span>) =></span> {</span><br><span class="line"> <span class="keyword">let</span> timer; <span class="comment">// 从原来的全局变量变成了闭包,是不是闭包理解又深刻了!</span></span><br><span class="line"> <span class="comment">// 注意这里不能用箭头函数</span></span><br><span class="line"> <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="comment">// console.log(timer); // 可以看看每次的timer是什么</span></span><br><span class="line"> <span class="keyword">if</span> (timer) {</span><br><span class="line"> <span class="keyword">return</span>; <span class="comment">//改动一:如果定时器还在,就啥也不干</span></span><br><span class="line"> }</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>); <span class="comment">//apply,call,bind的区别是什么,哈哈哈引申狂魔</span></span><br><span class="line"> timer = <span class="literal">null</span>; <span class="comment">//改动二,每次真正执行完,得把计时器变量重置一下,好在下次判断时知道上次的定时已经执行了</span></span><br><span class="line"> }, wait);</span><br><span class="line"> };</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test1 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test1"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test2 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test2"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> target = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"body"</span>)[<span class="number">0</span>];</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test1);</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, throttle(test2, <span class="number">1000</span>));</span><br></pre></td></tr></table></figure>
<ul>
<li>上述例子其实利用了一点,就是当触发时间小于设定时间时,就忽略,只有大于或等于设定时间时才会真正执行,即我们设定的定时器回调一定会执行。</li>
<li>这其实又是延后执行的思路。那立即执行呢?当然要借助时间戳了。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 封装一个包裹函数,返回节流后的函数</span></span><br><span class="line"><span class="keyword">const</span> throttle = <span class="function">(<span class="params">func, wait, immediate</span>) =></span> {</span><br><span class="line"> <span class="keyword">let</span> timer; <span class="comment">// 从原来的全局变量变成了闭包,是不是闭包理解又深刻了!</span></span><br><span class="line"> <span class="keyword">let</span> previousStamp = <span class="number">0</span>;</span><br><span class="line"> <span class="comment">// 注意这里不能用箭头函数</span></span><br><span class="line"> <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (immediate) {</span><br><span class="line"> <span class="comment">// console.log(previousStamp); // 可以看看每次的previousStamp是什么</span></span><br><span class="line"> <span class="keyword">const</span> now = <span class="built_in">Date</span>.now();</span><br><span class="line"> <span class="keyword">if</span> (now - previousStamp > wait) {</span><br><span class="line"> func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line"> previousStamp = now;</span><br><span class="line"> }</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> <span class="comment">// console.log(timer); // 可以看看每次的timer是什么</span></span><br><span class="line"> <span class="keyword">if</span> (timer) {</span><br><span class="line"> <span class="keyword">return</span>; <span class="comment">//改动一:如果定时器还在,就啥也不干</span></span><br><span class="line"> }</span><br><span class="line"> timer = <span class="built_in">setTimeout</span>(<span class="function">() =></span> {</span><br><span class="line"> func.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>); <span class="comment">//apply,call,bind的区别是什么,哈哈哈引申狂魔</span></span><br><span class="line"> timer = <span class="literal">null</span>; <span class="comment">//改动二,每次真正执行完,得把计时器变量重置一下,好在下次判断时知道上次的定时已经执行了</span></span><br><span class="line"> }, wait);</span><br><span class="line"> }</span><br><span class="line"> };</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test1 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test1"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> test2 = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>{</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"test2"</span>, e, <span class="built_in">this</span>);</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> target = <span class="built_in">document</span>.getElementsByTagName(<span class="string">"body"</span>)[<span class="number">0</span>];</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, test1);</span><br><span class="line">target.addEventListener(<span class="string">"keypress"</span>, throttle(test2, <span class="number">1000</span>, <span class="literal">true</span>));</span><br></pre></td></tr></table></figure>
<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h2><ul>
<li><p>对于防抖,适合多次事件只需一次响应的情况。如</p>
<ul>
<li>输入框连续输入需要远程校验</li>
<li>判断滚动条是否滑到某一位置</li>
<li>表单提交,连点多次</li>
</ul>
</li>
<li><p>对于节流,适合频繁事件可以按时间做减法归约来触发。</p>
<ul>
<li>元素拖拽事件</li>
<li>canvas 画画</li>
<li>游戏中动画刷新率</li>
</ul>
</li>
</ul>
<h2 id="防抖节流与事件循环"><a href="#防抖节流与事件循环" class="headerlink" title="防抖节流与事件循环"></a>防抖节流与事件循环</h2><ul>
<li>有文章提到了可以用 requestAnimationFrame 做节流,用 requestIdleCallback 做防抖,这都是很好的思路。浏览器的原生 api,实现了类似于防抖节流的机制,我们不用费劲自己写了。但是要想直接用于生产,肯定要考虑兼容性,还有功能是否完备等,这块可以引出事件循环后再细细讨论</li>
</ul>
<h2 id="防抖节流与设计模式"><a href="#防抖节流与设计模式" class="headerlink" title="防抖节流与设计模式"></a>防抖节流与设计模式</h2><ul>
<li>还有文章提到了装饰器模式和观察者模式。仔细想想,也都可以实现的。装饰器实际就是对函数的装饰(封装),观察者则是用防抖或节流函数充当观察者,满足一定条件后再去执行被观察的函数,可以专门写一篇来看看如何实现。</li>
<li>写了这么多,其实都是理解了原理后,通过一点点推论得出来的具体实现。而 underscore 和 lodash 的相关实现,都是将两者类比实现的,且用到很多精妙的技巧。直接贴上最新版代码吧。</li>
<li>underscore 的 debounce</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> restArguments <span class="keyword">from</span> <span class="string">"./restArguments.js"</span>;</span><br><span class="line"><span class="keyword">import</span> now <span class="keyword">from</span> <span class="string">"./now.js"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// When a sequence of calls of the returned function ends, the argument</span></span><br><span class="line"><span class="comment">// function is triggered. The end of a sequence is defined by the `wait`</span></span><br><span class="line"><span class="comment">// parameter. If `immediate` is passed, the argument function will be</span></span><br><span class="line"><span class="comment">// triggered at the beginning of the sequence instead of at the end.</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">func, wait, immediate</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> timeout, previous, args, result, context;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> later = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> passed = now() - previous;</span><br><span class="line"> <span class="keyword">if</span> (wait > passed) {</span><br><span class="line"> timeout = <span class="built_in">setTimeout</span>(later, wait - passed);</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> timeout = <span class="literal">null</span>;</span><br><span class="line"> <span class="keyword">if</span> (!immediate) result = func.apply(context, args);</span><br><span class="line"> <span class="comment">// This check is needed because `func` can recursively invoke `debounced`.</span></span><br><span class="line"> <span class="keyword">if</span> (!timeout) args = context = <span class="literal">null</span>;</span><br><span class="line"> }</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> debounced = restArguments(<span class="function"><span class="keyword">function</span> (<span class="params">_args</span>) </span>{</span><br><span class="line"> context = <span class="built_in">this</span>;</span><br><span class="line"> args = _args;</span><br><span class="line"> previous = now();</span><br><span class="line"> <span class="keyword">if</span> (!timeout) {</span><br><span class="line"> timeout = <span class="built_in">setTimeout</span>(later, wait);</span><br><span class="line"> <span class="keyword">if</span> (immediate) result = func.apply(context, args);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> });</span><br><span class="line"></span><br><span class="line"> debounced.cancel = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timeout);</span><br><span class="line"> timeout = args = context = <span class="literal">null</span>;</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> debounced;</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<ul>
<li>underscore 的 throttle</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> now <span class="keyword">from</span> <span class="string">"./now.js"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Returns a function, that, when invoked, will only be triggered at most once</span></span><br><span class="line"><span class="comment">// during a given window of time. Normally, the throttled function will run</span></span><br><span class="line"><span class="comment">// as much as it can, without ever going more than once per `wait` duration;</span></span><br><span class="line"><span class="comment">// but if you'd like to disable the execution on the leading edge, pass</span></span><br><span class="line"><span class="comment">// `{leading: false}`. To disable execution on the trailing edge, ditto.</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">throttle</span>(<span class="params">func, wait, options</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> timeout, context, args, result;</span><br><span class="line"> <span class="keyword">var</span> previous = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">if</span> (!options) options = {};</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> later = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> previous = options.leading === <span class="literal">false</span> ? <span class="number">0</span> : now();</span><br><span class="line"> timeout = <span class="literal">null</span>;</span><br><span class="line"> result = func.apply(context, args);</span><br><span class="line"> <span class="keyword">if</span> (!timeout) context = args = <span class="literal">null</span>;</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> throttled = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> _now = now();</span><br><span class="line"> <span class="keyword">if</span> (!previous && options.leading === <span class="literal">false</span>) previous = _now;</span><br><span class="line"> <span class="keyword">var</span> remaining = wait - (_now - previous);</span><br><span class="line"> context = <span class="built_in">this</span>;</span><br><span class="line"> args = <span class="built_in">arguments</span>;</span><br><span class="line"> <span class="keyword">if</span> (remaining <= <span class="number">0</span> || remaining > wait) {</span><br><span class="line"> <span class="keyword">if</span> (timeout) {</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timeout);</span><br><span class="line"> timeout = <span class="literal">null</span>;</span><br><span class="line"> }</span><br><span class="line"> previous = _now;</span><br><span class="line"> result = func.apply(context, args);</span><br><span class="line"> <span class="keyword">if</span> (!timeout) context = args = <span class="literal">null</span>;</span><br><span class="line"> } <span class="keyword">else</span> <span class="keyword">if</span> (!timeout && options.trailing !== <span class="literal">false</span>) {</span><br><span class="line"> timeout = <span class="built_in">setTimeout</span>(later, remaining);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> throttled.cancel = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="built_in">clearTimeout</span>(timeout);</span><br><span class="line"> previous = <span class="number">0</span>;</span><br><span class="line"> timeout = context = args = <span class="literal">null</span>;</span><br><span class="line"> };</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> throttled;</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<ul>
<li>lodash 的 debounce</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> isObject <span class="keyword">from</span> <span class="string">"./isObject.js"</span>;</span><br><span class="line"><span class="keyword">import</span> root <span class="keyword">from</span> <span class="string">"./.internal/root.js"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates a debounced function that delays invoking `func` until after `wait`</span></span><br><span class="line"><span class="comment"> * milliseconds have elapsed since the last time the debounced function was</span></span><br><span class="line"><span class="comment"> * invoked, or until the next browser frame is drawn. The debounced function</span></span><br><span class="line"><span class="comment"> * comes with a `cancel` method to cancel delayed `func` invocations and a</span></span><br><span class="line"><span class="comment"> * `flush` method to immediately invoke them. Provide `options` to indicate</span></span><br><span class="line"><span class="comment"> * whether `func` should be invoked on the leading and/or trailing edge of the</span></span><br><span class="line"><span class="comment"> * `wait` timeout. The `func` is invoked with the last arguments provided to the</span></span><br><span class="line"><span class="comment"> * debounced function. Subsequent calls to the debounced function return the</span></span><br><span class="line"><span class="comment"> * result of the last `func` invocation.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * **Note:** If `leading` and `trailing` options are `true`, `func` is</span></span><br><span class="line"><span class="comment"> * invoked on the trailing edge of the timeout only if the debounced function</span></span><br><span class="line"><span class="comment"> * is invoked more than once during the `wait` timeout.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred</span></span><br><span class="line"><span class="comment"> * until the next tick, similar to `setTimeout` with a timeout of `0`.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`</span></span><br><span class="line"><span class="comment"> * invocation will be deferred until the next frame is drawn (typically about</span></span><br><span class="line"><span class="comment"> * 16ms).</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)</span></span><br><span class="line"><span class="comment"> * for details over the differences between `debounce` and `throttle`.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since </span>0.1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@category <span class="variable">Function</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Function}</span> </span>func The function to debounce.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> </span>[wait=0]</span></span><br><span class="line"><span class="comment"> * The number of milliseconds to delay; if omitted, `requestAnimationFrame` is</span></span><br><span class="line"><span class="comment"> * used (if available).</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Object}</span> </span>[options={}] The options object.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{boolean}</span> </span>[options.leading=false]</span></span><br><span class="line"><span class="comment"> * Specify invoking on the leading edge of the timeout.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> </span>[options.maxWait]</span></span><br><span class="line"><span class="comment"> * The maximum time `func` is allowed to be delayed before it's invoked.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{boolean}</span> </span>[options.trailing=true]</span></span><br><span class="line"><span class="comment"> * Specify invoking on the trailing edge of the timeout.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Function}</span> </span>Returns the new debounced function.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example</span></span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Avoid costly calculations while the window size is in flux.</span></span><br><span class="line"><span class="comment"> * jQuery(window).on('resize', debounce(calculateLayout, 150))</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Invoke `sendMail` when clicked, debouncing subsequent calls.</span></span><br><span class="line"><span class="comment"> * jQuery(element).on('click', debounce(sendMail, 300, {</span></span><br><span class="line"><span class="comment"> * 'leading': true,</span></span><br><span class="line"><span class="comment"> * 'trailing': false</span></span><br><span class="line"><span class="comment"> * }))</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Ensure `batchLog` is invoked once after 1 second of debounced calls.</span></span><br><span class="line"><span class="comment"> * const debounced = debounce(batchLog, 250, { 'maxWait': 1000 })</span></span><br><span class="line"><span class="comment"> * const source = new EventSource('/stream')</span></span><br><span class="line"><span class="comment"> * jQuery(source).on('message', debounced)</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Cancel the trailing debounced invocation.</span></span><br><span class="line"><span class="comment"> * jQuery(window).on('popstate', debounced.cancel)</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Check for pending invocations.</span></span><br><span class="line"><span class="comment"> * const status = debounced.pending() ? "Pending..." : "Ready"</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">debounce</span>(<span class="params">func, wait, options</span>) </span>{</span><br><span class="line"> <span class="keyword">let</span> lastArgs, lastThis, maxWait, result, timerId, lastCallTime;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">let</span> lastInvokeTime = <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">let</span> leading = <span class="literal">false</span>;</span><br><span class="line"> <span class="keyword">let</span> maxing = <span class="literal">false</span>;</span><br><span class="line"> <span class="keyword">let</span> trailing = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Bypass `requestAnimationFrame` by explicitly setting `wait=0`.</span></span><br><span class="line"> <span class="keyword">const</span> useRAF =</span><br><span class="line"> !wait && wait !== <span class="number">0</span> && <span class="keyword">typeof</span> root.requestAnimationFrame === <span class="string">"function"</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">typeof</span> func !== <span class="string">"function"</span>) {</span><br><span class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">"Expected a function"</span>);</span><br><span class="line"> }</span><br><span class="line"> wait = +wait || <span class="number">0</span>;</span><br><span class="line"> <span class="keyword">if</span> (isObject(options)) {</span><br><span class="line"> leading = !!options.leading;</span><br><span class="line"> maxing = <span class="string">"maxWait"</span> <span class="keyword">in</span> options;</span><br><span class="line"> maxWait = maxing ? <span class="built_in">Math</span>.max(+options.maxWait || <span class="number">0</span>, wait) : maxWait;</span><br><span class="line"> trailing = <span class="string">"trailing"</span> <span class="keyword">in</span> options ? !!options.trailing : trailing;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">invokeFunc</span>(<span class="params">time</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> args = lastArgs;</span><br><span class="line"> <span class="keyword">const</span> thisArg = lastThis;</span><br><span class="line"></span><br><span class="line"> lastArgs = lastThis = <span class="literal">undefined</span>;</span><br><span class="line"> lastInvokeTime = time;</span><br><span class="line"> result = func.apply(thisArg, args);</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">startTimer</span>(<span class="params">pendingFunc, wait</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (useRAF) {</span><br><span class="line"> root.cancelAnimationFrame(timerId);</span><br><span class="line"> <span class="keyword">return</span> root.requestAnimationFrame(pendingFunc);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">setTimeout</span>(pendingFunc, wait);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">cancelTimer</span>(<span class="params">id</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (useRAF) {</span><br><span class="line"> <span class="keyword">return</span> root.cancelAnimationFrame(id);</span><br><span class="line"> }</span><br><span class="line"> <span class="built_in">clearTimeout</span>(id);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">leadingEdge</span>(<span class="params">time</span>) </span>{</span><br><span class="line"> <span class="comment">// Reset any `maxWait` timer.</span></span><br><span class="line"> lastInvokeTime = time;</span><br><span class="line"> <span class="comment">// Start the timer for the trailing edge.</span></span><br><span class="line"> timerId = startTimer(timerExpired, wait);</span><br><span class="line"> <span class="comment">// Invoke the leading edge.</span></span><br><span class="line"> <span class="keyword">return</span> leading ? invokeFunc(time) : result;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">remainingWait</span>(<span class="params">time</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> timeSinceLastCall = time - lastCallTime;</span><br><span class="line"> <span class="keyword">const</span> timeSinceLastInvoke = time - lastInvokeTime;</span><br><span class="line"> <span class="keyword">const</span> timeWaiting = wait - timeSinceLastCall;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> maxing</span><br><span class="line"> ? <span class="built_in">Math</span>.min(timeWaiting, maxWait - timeSinceLastInvoke)</span><br><span class="line"> : timeWaiting;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">shouldInvoke</span>(<span class="params">time</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> timeSinceLastCall = time - lastCallTime;</span><br><span class="line"> <span class="keyword">const</span> timeSinceLastInvoke = time - lastInvokeTime;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Either this is the first call, activity has stopped and we're at the</span></span><br><span class="line"> <span class="comment">// trailing edge, the system time has gone backwards and we're treating</span></span><br><span class="line"> <span class="comment">// it as the trailing edge, or we've hit the `maxWait` limit.</span></span><br><span class="line"> <span class="keyword">return</span> (</span><br><span class="line"> lastCallTime === <span class="literal">undefined</span> ||</span><br><span class="line"> timeSinceLastCall >= wait ||</span><br><span class="line"> timeSinceLastCall < <span class="number">0</span> ||</span><br><span class="line"> (maxing && timeSinceLastInvoke >= maxWait)</span><br><span class="line"> );</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">timerExpired</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> time = <span class="built_in">Date</span>.now();</span><br><span class="line"> <span class="keyword">if</span> (shouldInvoke(time)) {</span><br><span class="line"> <span class="keyword">return</span> trailingEdge(time);</span><br><span class="line"> }</span><br><span class="line"> <span class="comment">// Restart the timer.</span></span><br><span class="line"> timerId = startTimer(timerExpired, remainingWait(time));</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">trailingEdge</span>(<span class="params">time</span>) </span>{</span><br><span class="line"> timerId = <span class="literal">undefined</span>;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Only invoke if we have `lastArgs` which means `func` has been</span></span><br><span class="line"> <span class="comment">// debounced at least once.</span></span><br><span class="line"> <span class="keyword">if</span> (trailing && lastArgs) {</span><br><span class="line"> <span class="keyword">return</span> invokeFunc(time);</span><br><span class="line"> }</span><br><span class="line"> lastArgs = lastThis = <span class="literal">undefined</span>;</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">cancel</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (timerId !== <span class="literal">undefined</span>) {</span><br><span class="line"> cancelTimer(timerId);</span><br><span class="line"> }</span><br><span class="line"> lastInvokeTime = <span class="number">0</span>;</span><br><span class="line"> lastArgs = lastCallTime = lastThis = timerId = <span class="literal">undefined</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">flush</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> timerId === <span class="literal">undefined</span> ? result : trailingEdge(<span class="built_in">Date</span>.now());</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">pending</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> timerId !== <span class="literal">undefined</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">debounced</span>(<span class="params">...args</span>) </span>{</span><br><span class="line"> <span class="keyword">const</span> time = <span class="built_in">Date</span>.now();</span><br><span class="line"> <span class="keyword">const</span> isInvoking = shouldInvoke(time);</span><br><span class="line"></span><br><span class="line"> lastArgs = args;</span><br><span class="line"> lastThis = <span class="built_in">this</span>;</span><br><span class="line"> lastCallTime = time;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (isInvoking) {</span><br><span class="line"> <span class="keyword">if</span> (timerId === <span class="literal">undefined</span>) {</span><br><span class="line"> <span class="keyword">return</span> leadingEdge(lastCallTime);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (maxing) {</span><br><span class="line"> <span class="comment">// Handle invocations in a tight loop.</span></span><br><span class="line"> timerId = startTimer(timerExpired, wait);</span><br><span class="line"> <span class="keyword">return</span> invokeFunc(lastCallTime);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (timerId === <span class="literal">undefined</span>) {</span><br><span class="line"> timerId = startTimer(timerExpired, wait);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> }</span><br><span class="line"> debounced.cancel = cancel;</span><br><span class="line"> debounced.flush = flush;</span><br><span class="line"> debounced.pending = pending;</span><br><span class="line"> <span class="keyword">return</span> debounced;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> debounce;</span><br></pre></td></tr></table></figure>
<ul>
<li>lodash 的 throttle</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> debounce <span class="keyword">from</span> <span class="string">"./debounce.js"</span>;</span><br><span class="line"><span class="keyword">import</span> isObject <span class="keyword">from</span> <span class="string">"./isObject.js"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Creates a throttled function that only invokes `func` at most once per</span></span><br><span class="line"><span class="comment"> * every `wait` milliseconds (or once per browser frame). The throttled function</span></span><br><span class="line"><span class="comment"> * comes with a `cancel` method to cancel delayed `func` invocations and a</span></span><br><span class="line"><span class="comment"> * `flush` method to immediately invoke them. Provide `options` to indicate</span></span><br><span class="line"><span class="comment"> * whether `func` should be invoked on the leading and/or trailing edge of the</span></span><br><span class="line"><span class="comment"> * `wait` timeout. The `func` is invoked with the last arguments provided to the</span></span><br><span class="line"><span class="comment"> * throttled function. Subsequent calls to the throttled function return the</span></span><br><span class="line"><span class="comment"> * result of the last `func` invocation.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * **Note:** If `leading` and `trailing` options are `true`, `func` is</span></span><br><span class="line"><span class="comment"> * invoked on the trailing edge of the timeout only if the throttled function</span></span><br><span class="line"><span class="comment"> * is invoked more than once during the `wait` timeout.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred</span></span><br><span class="line"><span class="comment"> * until the next tick, similar to `setTimeout` with a timeout of `0`.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * If `wait` is omitted in an environment with `requestAnimationFrame`, `func`</span></span><br><span class="line"><span class="comment"> * invocation will be deferred until the next frame is drawn (typically about</span></span><br><span class="line"><span class="comment"> * 16ms).</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)</span></span><br><span class="line"><span class="comment"> * for details over the differences between `throttle` and `debounce`.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since </span>0.1.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@category <span class="variable">Function</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Function}</span> </span>func The function to throttle.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{number}</span> </span>[wait=0]</span></span><br><span class="line"><span class="comment"> * The number of milliseconds to throttle invocations to; if omitted,</span></span><br><span class="line"><span class="comment"> * `requestAnimationFrame` is used (if available).</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{Object}</span> </span>[options={}] The options object.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{boolean}</span> </span>[options.leading=true]</span></span><br><span class="line"><span class="comment"> * Specify invoking on the leading edge of the timeout.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">{boolean}</span> </span>[options.trailing=true]</span></span><br><span class="line"><span class="comment"> * Specify invoking on the trailing edge of the timeout.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">{Function}</span> </span>Returns the new throttled function.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example</span></span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Avoid excessively updating the position while scrolling.</span></span><br><span class="line"><span class="comment"> * jQuery(window).on('scroll', throttle(updatePosition, 100))</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.</span></span><br><span class="line"><span class="comment"> * const throttled = throttle(renewToken, 300000, { 'trailing': false })</span></span><br><span class="line"><span class="comment"> * jQuery(element).on('click', throttled)</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // Cancel the trailing throttled invocation.</span></span><br><span class="line"><span class="comment"> * jQuery(window).on('popstate', throttled.cancel)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">throttle</span>(<span class="params">func, wait, options</span>) </span>{</span><br><span class="line"> <span class="keyword">let</span> leading = <span class="literal">true</span>;</span><br><span class="line"> <span class="keyword">let</span> trailing = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">typeof</span> func !== <span class="string">"function"</span>) {</span><br><span class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">"Expected a function"</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (isObject(options)) {</span><br><span class="line"> leading = <span class="string">"leading"</span> <span class="keyword">in</span> options ? !!options.leading : leading;</span><br><span class="line"> trailing = <span class="string">"trailing"</span> <span class="keyword">in</span> options ? !!options.trailing : trailing;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> debounce(func, wait, {</span><br><span class="line"> leading,</span><br><span class="line"> trailing,</span><br><span class="line"> maxWait: wait,</span><br><span class="line"> });</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> throttle;</span><br></pre></td></tr></table></figure>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2021/03/20/debouce-throttle/" data-id="ckmheck1x0000zwre12eh055j" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/debounce/" rel="tag">debounce</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/throttle/" rel="tag">throttle</a></li></ul>
</footer>
</div>
</article>
<article id="post-1px-rem" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2021/03/15/1px-rem/" class="article-date">
<time datetime="2021-03-15T10:25:17.000Z" itemprop="datePublished">2021-03-15</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2021/03/15/1px-rem/">由1px问题引发的rem方案</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h2 id="面试官问,写过-h5-吧?1px-问题遇到过吧?怎么解决呢?"><a href="#面试官问,写过-h5-吧?1px-问题遇到过吧?怎么解决呢?" class="headerlink" title="面试官问,写过 h5 吧?1px 问题遇到过吧?怎么解决呢?"></a>面试官问,写过 h5 吧?1px 问题遇到过吧?怎么解决呢?</h2><ul>
<li>灵魂三问!别急,慢慢分析。</li>
</ul>
<h2 id="什么是-1px-问题?"><a href="#什么是-1px-问题?" class="headerlink" title="什么是 1px 问题?"></a>什么是 1px 问题?</h2><ul>
<li>一句话总结,就是涉及到 1px 的属性,在某些手机浏览器里,不能正常显示,有时太细甚至不显示;有时太粗,明显宽于 1px。即 1px 这个度量单位失真了。</li>
<li>再延伸一下,这其实是一类失真问题的统称,不止局限于 1px,我们讨论的意义在于,知其原因,晓其方法。</li>
</ul>
<h2 id="基本概念-ppi-dpr"><a href="#基本概念-ppi-dpr" class="headerlink" title="基本概念 ppi dpr"></a>基本概念 ppi dpr</h2><ul>
<li>深入讨论之前,先看几个概念。ppi、dpr、dip</li>
<li>ppi:pixels per inch。每英寸对角线上所拥有的像素。计算公式为:<img src="/img/ppi.png" alt="ppi" title="ppi"> 手机屏幕的 ppi 当达到一定数值时,人眼就分辨不出颗粒感。</li>
<li>dpr:device pixel ratio。设备像素比。有些高清屏幕为了追求高 ppi,增大了设备像素。在原本 1 个格子里加倍了像素,让人眼感觉更加清晰。比如原来是 1x1 的方格,dpr 为 2 时就是 2x2。</li>
<li>dip:device independent pixel。设备独立像素,是指一种换算机制。由于高清屏幕像素点过多,如果按照原来的像素数显示,由于屏幕实际尺寸不会变的很大(至少不会 2、3 倍的增加),所以会导致图像过小,以至于人眼反而看不清。所以设备自动进行了换算,得出了这个意为与设备无关的像素值,也可用来描述图像相对的大小。</li>
</ul>
<h2 id="何时发生?"><a href="#何时发生?" class="headerlink" title="何时发生?"></a>何时发生?</h2><ul>
<li>我们写的 css 像素,实际上就是换算后的 dip。设备根据不同 dpr,再反推出到底应该渲染多少实际的设备像素。</li>
<li>当高清屏 dpr 大于 1 时。相当于放大了整个页面,所有单位相当于放大了 dpr 倍。此时写个 1px,如果 dpr 是 2,那么等于设备应该渲染 0.5px 的 dip。</li>
<li>然而,问题关键来了。有时这个 0.5 会被四舍五入为 1。这样就整整差了 2 倍。所以看起来线条变粗了。</li>
</ul>
<h2 id="如何解决"><a href="#如何解决" class="headerlink" title="如何解决"></a>如何解决</h2><h4 id="方案一大类:跳过会出问题的属性,如-border。用其他方案替代"><a href="#方案一大类:跳过会出问题的属性,如-border。用其他方案替代" class="headerlink" title="方案一大类:跳过会出问题的属性,如 border。用其他方案替代"></a>方案一大类:跳过会出问题的属性,如 border。用其他方案替代</h4><ul>
<li>把 border 颜色设为透明,然后加上 border-image。缺点:有点 low,生生把灵活的 css 变成了硬编码,随便改个啥就得换图。</li>
<li>box-shadow 模拟 border,四个方向分别写阴影。缺点:不能圆角了,即 border-radius 无法模拟。颜色也不准确,因为有阴影。</li>
<li>使用伪元素,造个“替身”。先放大 n 倍,再 transform 缩小 1/n。缺点:有些 html 元素不能用伪元素。</li>
<li>用 svg 整个绘图,画出个 1px。然后作为背景图使用,是上面第一个方法的升级。有个插件 postcss-write-svg,可以将 svg 画好插入 css。</li>
</ul>
<h4 id="方案二大类:模拟-0-5px-或-0-33px,使其生效"><a href="#方案二大类:模拟-0-5px-或-0-33px,使其生效" class="headerlink" title="方案二大类:模拟 0.5px 或 0.33px,使其生效"></a>方案二大类:模拟 0.5px 或 0.33px,使其生效</h4><ul>
<li>WWDC2014 上提到了,直接就用 0.5px,ios8 以上支持小数 px,缺点:安卓不鸟你</li>
<li>使用 rem。根据 dpr 动态换算 viewport 的缩放比。如为 2 就缩小到 0.5 倍,为 3 就 0.333。由于整个页面已被缩小,故 1px 会正常显示为缩小后的长度。设计师很满意!程序员喘口气!实测,修改后实际是改变了屏幕视口的宽高,即修改了 dip。也有缺点:缩放比太小时,导致缩小后的 1px,小于了 0.5px,有时还是会被四舍五入舍去。可以规避,缩放比别太小即可。</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2021/03/15/1px-rem/" data-id="ckmau8yd800036nre3fgi2n4m" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/css/" rel="tag">css</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/h5/" rel="tag">h5</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rem/" rel="tag">rem</a></li></ul>
</footer>
</div>
</article>
<article id="post-pubsub-vs-observer" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2021/03/13/pubsub-vs-observer/" class="article-date">
<time datetime="2021-03-12T23:57:16.000Z" itemprop="datePublished">2021-03-13</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2021/03/13/pubsub-vs-observer/">pubsub-vs-observer</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h2 id="面试官问,发布订阅和观察者有啥区别?"><a href="#面试官问,发布订阅和观察者有啥区别?" class="headerlink" title="面试官问,发布订阅和观察者有啥区别?"></a>面试官问,发布订阅和观察者有啥区别?</h2><p>一脸懵逼?仔细想想,不难。且听娓娓道来。</p>
<h2 id="什么是发布订阅"><a href="#什么是发布订阅" class="headerlink" title="什么是发布订阅"></a>什么是发布订阅</h2><ul>
<li>你想知道某事发生,就需要实时监控着,时不时去看看,到底发没发生?</li>
<li>但这很傻,到底应该多久看一次呢?而且总去看也不是事儿,所以你问我能不能主动告诉你呢?</li>
<li>答案终于呼之欲出:能啊,你订阅我,我就给你发布!</li>
</ul>
<h2 id="每个人都用过!"><a href="#每个人都用过!" class="headerlink" title="每个人都用过!"></a>每个人都用过!</h2><ul>
<li>js 的事件模型其实就是发布订阅!事件都是不一定啥时发生的,所以我们想要监控事件的发生,就要提前写好相应的回调,相当于订阅了这个事件的发生。而 js 引擎就负责实现其中逻辑。最终事件由触发者来触发,这里可以是真实事件,也可以是代码模拟出的。所以发布订阅也可称为自定义事件。</li>
</ul>
<h2 id="最简单的发布订阅"><a href="#最简单的发布订阅" class="headerlink" title="最简单的发布订阅"></a>最简单的发布订阅</h2><ul>
<li>A 想知道 B 是否发生,很简单,A 订阅 B,B 发布即可。代码如下:</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// B为发布者</span></span><br><span class="line"><span class="keyword">const</span> B = {</span><br><span class="line"> cbList: [], <span class="comment">// 需把所有订阅者想做的事都存起来</span></span><br><span class="line"> <span class="function"><span class="title">onSub</span>(<span class="params">cb</span>)</span> {</span><br><span class="line"> <span class="comment">// 被订阅时的动作</span></span><br><span class="line"> <span class="built_in">this</span>.cbList.push(cb);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">pub</span>(<span class="params"></span>)</span> {</span><br><span class="line"> <span class="comment">// 发布时依次执行列表里的回调</span></span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index < <span class="built_in">this</span>.cbList.length; index++) {</span><br><span class="line"> <span class="keyword">const</span> cb = <span class="built_in">this</span>.cbList[index];</span><br><span class="line"> cb.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line"><span class="comment">// A为订阅者,诉求很简单,告诉我!</span></span><br><span class="line"><span class="keyword">const</span> A = {</span><br><span class="line"> <span class="function"><span class="title">tellMe</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMe"</span>, msg);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">tellMeAgain</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMeAgain"</span>, msg);</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line">B.onSub(A.tellMe); <span class="comment">// A订阅了B</span></span><br><span class="line">B.onSub(A.tellMeAgain); <span class="comment">// A又订阅了B</span></span><br><span class="line">B.pub(<span class="string">"我发生了"</span>);</span><br></pre></td></tr></table></figure>
<h2 id="两个小问题"><a href="#两个小问题" class="headerlink" title="两个小问题"></a>两个小问题</h2><ul>
<li>现在 A 只知道 B 发生了,其他关于 B 的事情一概不知。假设还想知道 B 结束了,咋办?</li>
<li>A 一旦订阅了 B,再想反悔不想订阅了,好像做不到。</li>
<li>所以,上述最简单的例子可以再改改,加个订阅的类型,以及支持取消订阅。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// B为发布者</span></span><br><span class="line"><span class="keyword">const</span> B = {</span><br><span class="line"> cbObj: {}, <span class="comment">// 需把所有订阅者想做的事都存起来</span></span><br><span class="line"> <span class="function"><span class="title">onSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="comment">// 被订阅时的动作</span></span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type] = [];</span><br><span class="line"> }</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].push(cb);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">onCancelSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> len = <span class="built_in">this</span>.cbObj[type].length; len > <span class="number">0</span>; len--) {</span><br><span class="line"> <span class="keyword">const</span> fn = <span class="built_in">this</span>.cbObj[type][len - <span class="number">1</span>];</span><br><span class="line"> <span class="keyword">if</span> (fn === cb) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].splice(len - <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">pub</span>(<span class="params">...rest</span>)</span> {</span><br><span class="line"> <span class="comment">// 发布时依次执行列表里的回调</span></span><br><span class="line"> <span class="keyword">const</span> type = rest.shift();</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index < <span class="built_in">this</span>.cbObj[type].length; index++) {</span><br><span class="line"> <span class="keyword">const</span> cb = <span class="built_in">this</span>.cbObj[type][index];</span><br><span class="line"> cb.apply(<span class="built_in">this</span>, rest);</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line"><span class="comment">// A为订阅者,诉求很简单,告诉我!</span></span><br><span class="line"><span class="keyword">const</span> A = {</span><br><span class="line"> <span class="function"><span class="title">tellMe</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMe"</span>, msg);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">tellMeAgain</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMeAgain"</span>, msg);</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line">B.onSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A订阅了B</span></span><br><span class="line">B.onCancelSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A取消订阅了B</span></span><br><span class="line">B.onSub(<span class="string">"over"</span>, A.tellMeAgain); <span class="comment">// A又订阅了B</span></span><br><span class="line">B.pub(<span class="string">"start"</span>, <span class="string">"我发生了"</span>);</span><br><span class="line">B.pub(<span class="string">"over"</span>, <span class="string">"我结束了"</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>至此,其实已经实现了一般意义上的观察者模式,发现了吗?最简单的发布订阅就是观察者模式!</li>
<li>那标准意义上的发布订阅还有什么区别呢?答案马上揭晓</li>
<li>上述的例子有点死板,因为无论谁订阅,订阅谁,总是要直接调用相关对象的方法,这就形成了深耦合,不利于扩展,所以能否做一些统一的封装工作,帮助我们管理这些订阅发布的动作?</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// B改为通用的发布者</span></span><br><span class="line"><span class="keyword">const</span> PUB = {</span><br><span class="line"> cbObj: {}, <span class="comment">// 需把所有订阅者想做的事都存起来</span></span><br><span class="line"> <span class="function"><span class="title">onSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="comment">// 被订阅时的动作</span></span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type] = [];</span><br><span class="line"> }</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].push(cb);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">onCancelSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> len = <span class="built_in">this</span>.cbObj[type].length; len > <span class="number">0</span>; len--) {</span><br><span class="line"> <span class="keyword">const</span> fn = <span class="built_in">this</span>.cbObj[type][len - <span class="number">1</span>];</span><br><span class="line"> <span class="keyword">if</span> (fn === cb) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].splice(len - <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">pub</span>(<span class="params">...rest</span>)</span> {</span><br><span class="line"> <span class="comment">// 发布时依次执行列表里的回调</span></span><br><span class="line"> <span class="keyword">const</span> type = rest.shift();</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index < <span class="built_in">this</span>.cbObj[type].length; index++) {</span><br><span class="line"> <span class="keyword">const</span> cb = <span class="built_in">this</span>.cbObj[type][index];</span><br><span class="line"> cb.apply(<span class="built_in">this</span>, rest);</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line"><span class="comment">// 部署通用版发布</span></span><br><span class="line"><span class="keyword">var</span> deployPub = <span class="function"><span class="keyword">function</span> (<span class="params">obj</span>) </span>{</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> PUB) {</span><br><span class="line"> obj[i] = PUB[i];</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line"><span class="keyword">const</span> B = {};</span><br><span class="line">deployPub(B); <span class="comment">//这样B就具有了发布功能</span></span><br><span class="line"><span class="comment">// 继续用A测试</span></span><br><span class="line"><span class="keyword">const</span> A = {</span><br><span class="line"> <span class="function"><span class="title">tellMe</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMe"</span>, msg);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">tellMeAgain</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMeAgain"</span>, msg);</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line">B.onSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A订阅了B</span></span><br><span class="line">B.onCancelSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A取消订阅了B</span></span><br><span class="line">B.onSub(<span class="string">"over"</span>, A.tellMeAgain); <span class="comment">// A又订阅了B</span></span><br><span class="line">B.pub(<span class="string">"start"</span>, <span class="string">"我发生了"</span>);</span><br><span class="line">B.pub(<span class="string">"over"</span>, <span class="string">"我结束了"</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>再仔细观察一下,是不是貌似不需要把 B 每次都变成所谓的通用发布者,因为 A 订阅时,已经不关注订阅的对象是谁了,而只关注订阅的事件类型。</li>
<li>所以,可以进一步理解为发布订阅模式就是这样一种模式,即通过“中间人”的角色,完成所有类型事件的订阅。这个中间人只负责收集订阅者,和向所有订阅者发布消息。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// PUB即为中间人</span></span><br><span class="line"><span class="keyword">const</span> PUB = {</span><br><span class="line"> cbObj: {}, <span class="comment">// 需把所有订阅者想做的事都存起来</span></span><br><span class="line"> <span class="function"><span class="title">onSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="comment">// 被订阅时的动作</span></span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type] = [];</span><br><span class="line"> }</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].push(cb);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">onCancelSub</span>(<span class="params">type, cb</span>)</span> {</span><br><span class="line"> <span class="keyword">if</span> (!<span class="built_in">this</span>.cbObj[type]) {</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> len = <span class="built_in">this</span>.cbObj[type].length; len > <span class="number">0</span>; len--) {</span><br><span class="line"> <span class="keyword">const</span> fn = <span class="built_in">this</span>.cbObj[type][len - <span class="number">1</span>];</span><br><span class="line"> <span class="keyword">if</span> (fn === cb) {</span><br><span class="line"> <span class="built_in">this</span>.cbObj[type].splice(len - <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">pub</span>(<span class="params">...rest</span>)</span> {</span><br><span class="line"> <span class="comment">// 发布时依次执行列表里的回调</span></span><br><span class="line"> <span class="keyword">const</span> type = rest.shift();</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">let</span> index = <span class="number">0</span>; index < <span class="built_in">this</span>.cbObj[type].length; index++) {</span><br><span class="line"> <span class="keyword">const</span> cb = <span class="built_in">this</span>.cbObj[type][index];</span><br><span class="line"> cb.apply(<span class="built_in">this</span>, rest);</span><br><span class="line"> }</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line"><span class="comment">// 继续用A测试</span></span><br><span class="line"><span class="keyword">const</span> A = {</span><br><span class="line"> <span class="function"><span class="title">tellMe</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMe"</span>, msg);</span><br><span class="line"> },</span><br><span class="line"> <span class="function"><span class="title">tellMeAgain</span>(<span class="params">msg</span>)</span> {</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">"tellMeAgain"</span>, msg);</span><br><span class="line"> },</span><br><span class="line">};</span><br><span class="line">PUB.onSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A订阅了start</span></span><br><span class="line">PUB.onCancelSub(<span class="string">"start"</span>, A.tellMe); <span class="comment">// A取消订阅了start</span></span><br><span class="line">PUB.onSub(<span class="string">"over"</span>, A.tellMeAgain); <span class="comment">// A又订阅了over</span></span><br><span class="line">PUB.pub(<span class="string">"start"</span>, <span class="string">"我发生了"</span>);</span><br><span class="line">PUB.pub(<span class="string">"over"</span>, <span class="string">"我结束了"</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>其实还可以再加上更高级的一些功能,例如支持离线消息,即发布时还没订阅,订阅晚于发布时间;还有支持命名空间等,因为总是把所有类型的事件放在一起,用一个字符串表示,难免最后会乱。最后是终极代码,直接照抄了原书作者的版本。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Event = (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> <span class="built_in">global</span> = <span class="built_in">this</span>,</span><br><span class="line"> Event,</span><br><span class="line"> _default = <span class="string">"default"</span>;</span><br><span class="line"> Event = (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> _listen,</span><br><span class="line"> _trigger,</span><br><span class="line"> _remove,</span><br><span class="line"> _slice = <span class="built_in">Array</span>.prototype.slice,</span><br><span class="line"> _shift = <span class="built_in">Array</span>.prototype.shift,</span><br><span class="line"> _unshift = <span class="built_in">Array</span>.prototype.unshift,</span><br><span class="line"> namespaceCache = {},</span><br><span class="line"> _create,</span><br><span class="line"> find,</span><br><span class="line"> each = <span class="function"><span class="keyword">function</span> (<span class="params">ary, fn</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> ret;</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = ary.length; i < l; i++) {</span><br><span class="line"> <span class="keyword">var</span> n = ary[i];</span><br><span class="line"> ret = fn.call(n, i, n);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> ret;</span><br><span class="line"> };</span><br><span class="line"> _listen = <span class="function"><span class="keyword">function</span> (<span class="params">key, fn, cache</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (!cache[key]) {</span><br><span class="line"> cache[key] = [];</span><br><span class="line"> }</span><br><span class="line"> cache[key].push(fn);</span><br><span class="line"> };</span><br><span class="line"> _remove = <span class="function"><span class="keyword">function</span> (<span class="params">key, cache, fn</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (cache[key]) {</span><br><span class="line"> <span class="keyword">if</span> (fn) {</span><br><span class="line"> <span class="keyword">for</span> (<span class="keyword">var</span> i = cache[key].length; i >= <span class="number">0</span>; i--) {</span><br><span class="line"> <span class="keyword">if</span> (cache[key][i] === fn) {</span><br><span class="line"> cache[key].splice(i, <span class="number">1</span>);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> cache[key] = [];</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> };</span><br><span class="line"> _trigger = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> cache = _shift.call(<span class="built_in">arguments</span>),</span><br><span class="line"> key = _shift.call(<span class="built_in">arguments</span>),</span><br><span class="line"> args = <span class="built_in">arguments</span>,</span><br><span class="line"> _self = <span class="built_in">this</span>,</span><br><span class="line"> ret,</span><br><span class="line"> stack = cache[key];</span><br><span class="line"> <span class="keyword">if</span> (!stack || !stack.length) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> each(stack, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">this</span>.apply(_self, args);</span><br><span class="line"> });</span><br><span class="line"> };</span><br><span class="line"> _create = <span class="function"><span class="keyword">function</span> (<span class="params">namespace</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> namespace = namespace || _default;</span><br><span class="line"> <span class="keyword">var</span> cache = {},</span><br><span class="line"> offlineStack = [], <span class="comment">// 离线事件</span></span><br><span class="line"> ret = {</span><br><span class="line"> listen: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn, last</span>) </span>{</span><br><span class="line"> _listen(key, fn, cache);</span><br><span class="line"> <span class="keyword">if</span> (offlineStack === <span class="literal">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (last === <span class="string">"last"</span>) {</span><br><span class="line"> offlineStack.length && offlineStack.pop()();</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> each(offlineStack, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="built_in">this</span>();</span><br><span class="line"> });</span><br><span class="line"> }</span><br><span class="line"> offlineStack = <span class="literal">null</span>;</span><br><span class="line"> },</span><br><span class="line"> one: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn, last</span>) </span>{</span><br><span class="line"> _remove(key, cache);</span><br><span class="line"> <span class="built_in">this</span>.listen(key, fn, last);</span><br><span class="line"> },</span><br><span class="line"> remove: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn</span>) </span>{</span><br><span class="line"> _remove(key, cache, fn);</span><br><span class="line"> },</span><br><span class="line"> trigger: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> fn,</span><br><span class="line"> args,</span><br><span class="line"> _self = <span class="built_in">this</span>;</span><br><span class="line"> _unshift.call(<span class="built_in">arguments</span>, cache);</span><br><span class="line"> args = <span class="built_in">arguments</span>;</span><br><span class="line"> fn = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">return</span> _trigger.apply(_self, args);</span><br><span class="line"> };</span><br><span class="line"> <span class="keyword">if</span> (offlineStack) {</span><br><span class="line"> <span class="keyword">return</span> offlineStack.push(fn);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> fn();</span><br><span class="line"> },</span><br><span class="line"> };</span><br><span class="line"> <span class="keyword">return</span> namespace</span><br><span class="line"> ? namespaceCache[namespace]</span><br><span class="line"> ? namespaceCache[namespace]</span><br><span class="line"> : (namespaceCache[namespace] = ret)</span><br><span class="line"> : ret;</span><br><span class="line"> };</span><br><span class="line"> <span class="keyword">return</span> {</span><br><span class="line"> create: _create,</span><br><span class="line"> one: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn, last</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> event = <span class="built_in">this</span>.create();</span><br><span class="line"> event.one(key, fn, last);</span><br><span class="line"> },</span><br><span class="line"> remove: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> event = <span class="built_in">this</span>.create();</span><br><span class="line"> event.remove(key, fn);</span><br><span class="line"> },</span><br><span class="line"> listen: <span class="function"><span class="keyword">function</span> (<span class="params">key, fn, last</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> event = <span class="built_in">this</span>.create();</span><br><span class="line"> event.listen(key, fn, last);</span><br><span class="line"> },</span><br><span class="line"> trigger: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> event = <span class="built_in">this</span>.create();</span><br><span class="line"> event.trigger.apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line"> },</span><br><span class="line"> };</span><br><span class="line"> })();</span><br><span class="line"> <span class="keyword">return</span> Event;</span><br><span class="line">})();</span><br></pre></td></tr></table></figure>
<ul>
<li>最后总结一下,观察者模式是这种模式的最初思想,为了实现不同对象间的解耦合。</li>
<li>自此基础上发展出了发布订阅模式,通过中间人的角色,统一来管理所有消息的订阅和发布。</li>
<li>后续的功能,例如离线消息、命名空间等,更是为这一模式更加增光添彩如虎添翼。</li>
<li>总之,这种设计模式的思想非常经典,也应用于很多大型复杂软件之中,掌握这种模式还是非常必要的。</li>
</ul>
<h2 id="最后补充"><a href="#最后补充" class="headerlink" title="最后补充"></a>最后补充</h2><ul>
<li>其实还有一种写法是,订阅者和发布者的角色不局限于某一对象,即订阅者同时也可发布,发布者也可订阅。</li>
<li>看起来更好理解,更像是字面意思上的观察者,互相订阅,也是互相观察。</li>
<li>这种写法的最简版(观察者模式)就是互相观察,深度耦合;升级版也是使用中间人,统一管理订阅发布行为,从而进化为发布订阅模式。</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2021/03/13/pubsub-vs-observer/" data-id="ckmau8ydu000z6nre03gohyhc" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/design-pattern/" rel="tag">design pattern</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85-%E8%A7%82%E5%AF%9F%E8%80%85/" rel="tag">发布订阅/观察者</a></li></ul>
</footer>
</div>
</article>
<article id="post-antd-combobox" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2020/11/16/antd-combobox/" class="article-date">
<time datetime="2020-11-16T10:04:54.000Z" itemprop="datePublished">2020-11-16</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2020/11/16/antd-combobox/">antd-combobox</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h3 id="1-combobox"><a href="#1-combobox" class="headerlink" title="1. combobox"></a>1. combobox</h3><ul>
<li>使用antd时,需要一个combobox场景。即选择框也可输入自定义内容。</li>
<li>但是antd貌似没有这个组件,可以用AutoComplete组件来实现。</li>
</ul>
<h3 id="2-实现要点"><a href="#2-实现要点" class="headerlink" title="2. 实现要点"></a>2. 实现要点</h3><ul>
<li><figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><AutoComplete</span><br><span class="line"> value={payment_terms}</span><br><span class="line"> style={{ <span class="attr">width</span>: <span class="number">100</span> }}</span><br><span class="line"> onChange={<span class="function">(<span class="params">value</span>) =></span> {</span><br><span class="line"> <span class="built_in">this</span>.changePaymentTerm(<span class="string">`<span class="subst">${<span class="built_in">this</span>.validatePaymentTerms(value)}</span>`</span>);</span><br><span class="line"> }}</span><br><span class="line"> dataSource={paymentTermsList.map(<span class="function">(<span class="params">item</span>) =></span> <span class="string">`<span class="subst">${item}</span>`</span>)}</span><br><span class="line">></AutoComplete></span><br></pre></td></tr></table></figure></li>
<li>提前设置好dataSource,即可选择的列表。</li>
<li>因为AutoComplete就是可以输入来搜索的,所以就实现了既可以输入,也可以搜索的功能。</li>
<li>注意点:控制onChange,既可以实现输入内容校验和替换,也是设置了当输入自定义内容时,即为下拉选择无可选项。直接设置值即可。</li>
</ul>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 强制处理为数字</span></span><br><span class="line">validatePaymentTerms = <span class="function">(<span class="params">value</span>) =></span> {</span><br><span class="line"> <span class="keyword">if</span> (<span class="built_in">Number</span>.isNaN(<span class="built_in">Number</span>(value))) {</span><br><span class="line"> <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">if</span> (value < <span class="number">0</span>) {</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">Math</span>.abs(value);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">Math</span>.round(value);</span><br><span class="line">};</span><br></pre></td></tr></table></figure>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2020/11/16/antd-combobox/" data-id="ckmau8yde00086nre4twn2o8t" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/antd/" rel="tag">antd</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/react/" rel="tag">react</a></li></ul>
</footer>
</div>
</article>
<article id="post-bpmn-custom" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2019/10/30/bpmn-custom/" class="article-date">
<time datetime="2019-10-30T06:22:34.000Z" itemprop="datePublished">2019-10-30</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2019/10/30/bpmn-custom/">bpmn-js自定义开发</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h3 id="1-基于开源工具库-bpmn-js-5-0-版本,对源码进行修改、自定义,通过二次开发实现。"><a href="#1-基于开源工具库-bpmn-js-5-0-版本,对源码进行修改、自定义,通过二次开发实现。" class="headerlink" title="1. 基于开源工具库 bpmn-js 5.0 版本,对源码进行修改、自定义,通过二次开发实现。"></a>1. 基于开源工具库 <a target="_blank" rel="noopener" href="https://github.com/bpmn-io/bpmn-js">bpmn-js</a> 5.0 版本,对源码进行修改、自定义,通过二次开发实现。</h3><h3 id="2-代码主要改动介绍"><a href="#2-代码主要改动介绍" class="headerlink" title="2. 代码主要改动介绍"></a>2. 代码主要改动介绍</h3><ul>
<li>styles/assets 样式文件,左侧调色板的图标样式</li>
<li>lib/Viewer.js bpmn-moddle 是引用的第三方库,内含所有 bpmn 所用的图形,事件,动作等</li>
<li>lib/draw/BpmnRenderer.js 添加/修改 渲染类型</li>
<li>lib/features/context-pad/ContextPadProvider.js 添加/修改上下文面板菜单</li>
<li>lib/features/modeling/ElementFactory.js 修改图形的默认尺寸</li>
<li>lib/features/palette/PaletteProvider.js 修改调色板菜单内容,分组等</li>
<li>node_modules\bpmn-js-properties-panel\lib\provider\camunda\CamundaPropertiesProvider.js 修改右侧面板选项卡内容</li>
</ul>
<h3 id="3-修改后示例项目"><a href="#3-修改后示例项目" class="headerlink" title="3. 修改后示例项目"></a>3. 修改后示例项目</h3><ul>
<li>依赖引入自有 git 项目,每次库有更新,需要手动执行 npm up 来更新库</li>
<li>使用时可自定义节点属性,进行读写</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2019/10/30/bpmn-custom/" data-id="ckmau8ydm000k6nred71if95b" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/bpmn/" rel="tag">bpmn</a></li></ul>
</footer>
</div>
</article>
<article id="post-mini-program" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2019/07/11/mini-program/" class="article-date">
<time datetime="2019-07-11T03:44:34.000Z" itemprop="datePublished">2019-07-11</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2019/07/11/mini-program/">小程序框架情况调研</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<p>本文探索小程序框架和组件库,这里主要指微信小程序,后续不排除可能需要开发支付宝小程序/XX 小程序等等,所以多平台多端的兼容性也是一项考察指标。下文列举较为流行的框架和组件库。</p>
<h3 id="1-基本需求"><a href="#1-基本需求" class="headerlink" title="1. 基本需求"></a>1. 基本需求</h3><ul>
<li>尽量摆脱“微信语法”-WXML、WXSS、WXS。即使微信语法与 mvvm 框架语法类似,但仍免不了学习成本。</li>
<li>支持 vue 语法或 react 语法,可快速上手</li>
</ul>
<h3 id="2-进阶需求"><a href="#2-进阶需求" class="headerlink" title="2. 进阶需求"></a>2. 进阶需求</h3><ul>
<li>一套代码生成多平台应用</li>
<li>支持 npm</li>
<li>更多组件库支持</li>
</ul>
<h3 id="3-框架对比"><a href="#3-框架对比" class="headerlink" title="3. 框架对比"></a>3. 框架对比</h3><table>
<thead>
<tr>
<th>名称</th>
<th>github stars</th>
<th>语法规范</th>
<th>多平台支持</th>
<th>npm</th>
<th>备注</th>
<th>踩坑记录</th>
</tr>
</thead>
<tbody><tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/Tencent/wepy">Tencent / wepy</a></strong></td>
<td>18.2k</td>
<td>类 vue,WXML、WXSS、WXS</td>
<td>微信、支付宝</td>
<td>支持</td>
<td>支持 ES2015+特性,支持多种编译器,支持多种插件处理,支持 Sourcemap,ESLint 等小程序细节优化</td>
<td>1.新版本 2.0 暂不支持支付宝,还是 alpha 版 2.编辑器对.wepy 文件支持不够</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/Meituan-Dianping/mpvue">Meituan-Dianping / mpvue</a></strong></td>
<td>17.9k</td>
<td>vue</td>
<td>微信、百度、头条、支付宝</td>
<td>支持</td>
<td>完整的 Vue.js 开发体验 H5 代码转换编译成小程序目标代码的能力</td>
<td>1.文档将近一年没有维护 新版本 2.0 没有新文档 2.头条小程序报错 bug,暂未解决 3.百度真机调试困难</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/NervJS/taro">NervJS / taro</a></strong></td>
<td>20.0k</td>
<td>react</td>
<td>微信、百度、支付宝、头条、 移动端(React-Native)</td>
<td>npm/yarn</td>
<td>完整的 react 开发体验</td>
<td></td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/didi/chameleon">didi / chameleon</a></strong></td>
<td>5.4k</td>
<td>类 vue ,CML + CMSS + JS</td>
<td>微信、百度、支付宝、移动端(Weex)、快应用 qq(alpha)</td>
<td>支持</td>
<td>丰富的官方 api 库、组件库</td>
<td>构建工具安装困难</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/dcloudio/uni-app">dcloudio / uni-app</a></strong></td>
<td>9.3k</td>
<td>vue</td>
<td>微信、百度、支付宝、头条、 移动端(Weex)</td>
<td>支持</td>
<td>官方组件库、api 库 有专用定制 ide: HBuilder</td>
<td></td>
</tr>
</tbody></table>
<h3 id="4-组件库"><a href="#4-组件库" class="headerlink" title="4. 组件库"></a>4. 组件库</h3><table>
<thead>
<tr>
<th>名称</th>
<th>github stars</th>
<th>备注</th>
</tr>
</thead>
<tbody><tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/Tencent/weui-wxss">Tencent / weui-wxss</a></strong></td>
<td>10.0k</td>
<td>微信官方组件库 WeUI 的小程序版本</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/youzan/vant-weapp">youzan / vant-weapp</a></strong></td>
<td>9.7k</td>
<td>有赞移动端 Vue 组件库 Vant 的小程序版本</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/TalkingData/iview-weapp">TalkingData / iview-weapp</a></strong></td>
<td>4.6k</td>
<td>iview 小程序版</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/meili/minui">meili / minui</a></strong></td>
<td>3.2k</td>
<td>可通过自有构建工具单独安装单个组件</td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/wux-weapp/wux-weapp">wux-weapp / wux-weapp</a></strong></td>
<td>3.4k</td>
<td></td>
</tr>
<tr>
<td><strong><a target="_blank" rel="noopener" href="https://github.com/weilanwl/ColorUI">weilanwl / ColorUI</a></strong></td>
<td>4.7k</td>
<td>css 库</td>
</tr>
</tbody></table>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2019/07/11/mini-program/" data-id="ckmau8ydq000o6nre9h7s4i6z" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%B0%8F%E7%A8%8B%E5%BA%8F/" rel="tag">小程序</a></li></ul>
</footer>
</div>
</article>
<article id="post-wechat-js-sdk" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2019/02/18/wechat-js-sdk/" class="article-date">
<time datetime="2019-02-18T09:19:34.000Z" itemprop="datePublished">2019-02-18</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2019/02/18/wechat-js-sdk/">微信公众平台-微信JS-SDK接入</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h3 id="1-申请和认证"><a href="#1-申请和认证" class="headerlink" title="1. 申请和认证"></a>1. 申请和认证</h3><ul>
<li>在微信公众平台申请开发者 ID,通过订阅号或服务号认证后,可取得相应接口权限</li>
</ul>
<h3 id="2-相关配置"><a href="#2-相关配置" class="headerlink" title="2. 相关配置"></a>2. 相关配置</h3><ul>
<li>在微信公众平台登录认证过的公众号,进行开发者相关配置,至少填写如下信息</li>
<li>appID–属于该开发者 ID 的</li>
<li>appsecret–属于该开发者 ID 的</li>
<li>一个能够响应微信验证身份请求的服务接口地址,端口必须为 80(http)或 443(https)</li>
<li>一个自定义的 token,用于微信身份验证</li>
<li>加密方式,用于加密验证的消息。</li>
<li>注:按微信要求,验证接口需原样返回请求参数,故可不做校验,直接返回即可,但安全性不能保证,推荐真正校验通过再返回</li>
<li>JS 接口安全域名–一个公众号最多可绑定 3 个安全域名,每月有三次保存机会。绑定时还需将一个微信提供的文本文件置于项目根目录(视为静态资源),确保配置的安全域名根目录下能够访问该文件。</li>
<li>全部配置并至少保存成功一次,即为接入微信公众平台成功,可调用该公众号拥有权限的所有微信公众平台接口</li>
</ul>
<h3 id="3-采用-js-sdk-调用接口,需验证身份,包括如下步骤"><a href="#3-采用-js-sdk-调用接口,需验证身份,包括如下步骤" class="headerlink" title="3. 采用 js-sdk 调用接口,需验证身份,包括如下步骤"></a>3. 采用 js-sdk 调用接口,需验证身份,包括如下步骤</h3><ul>
<li>获取 access_token–公众号的全局唯一接口调用凭据。每次获取新的时,旧的在 5 分钟后失效,有效期 2 小时。微信要求开发者在全局缓存该 token,因获取 token 接口每日有调用次数限制 2000。</li>
<li>获取 jsapi_ticket–公众号用于调用微信 JS 接口的临时票据。同上,有效期 2 小时,调用次数限制 2000,也需要全局缓存</li>
<li>开发者需按照 <a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115">https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115</a> 所提供的算法在服务端进行签名,返回客户端此次调用微信接口的临时签名</li>
<li>至此,完成了微信公众平台-微信 JS-SDK 的接入</li>
</ul>
<h3 id="4-调用微信的接口之前,需调用如下接口"><a href="#4-调用微信的接口之前,需调用如下接口" class="headerlink" title="4. 调用微信的接口之前,需调用如下接口"></a>4. 调用微信的接口之前,需调用如下接口</h3><ul>
<li>调用 wx.config 接口,注入配置信息(包括签名、appId、本次需要调用的接口列表等)。同一个 url 仅需调用一次</li>
<li>调用 wx.ready 接口,在成功回调中,可调用所有本次想使用的微信接口功能,包括分享、图形、音频等。</li>
</ul>
<h3 id="5-页面引入-sdk-文件"><a href="#5-页面引入-sdk-文件" class="headerlink" title="5. 页面引入 sdk 文件"></a>5. 页面引入 sdk 文件</h3><ul>
<li>建议使用 <a target="_blank" rel="noopener" href="https://res.wx.qq.com/open/js/jweixin-1.4.0.js">https://res.wx.qq.com/open/js/jweixin-1.4.0.js</a> 可支持 https 或 http 域名</li>
<li>若使用 <a target="_blank" rel="noopener" href="http://res.wx.qq.com/open/js/jweixin-1.4.0.js">http://res.wx.qq.com/open/js/jweixin-1.4.0.js</a> 则不支持 https 域名</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2019/02/18/wechat-js-sdk/" data-id="ckmau8ydw00136nrean084gdg" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js-sdk/" rel="tag">js-sdk</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%BE%AE%E4%BF%A1/" rel="tag">微信</a></li></ul>
</footer>
</div>
</article>
<article id="post-mongoose" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2018/12/26/mongoose/" class="article-date">
<time datetime="2018-12-26T08:49:34.000Z" itemprop="datePublished">2018-12-26</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2018/12/26/mongoose/">mongoose</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h3 id="1-什么是-mongoose"><a href="#1-什么是-mongoose" class="headerlink" title="1. 什么是 mongoose"></a>1. 什么是 mongoose</h3><ul>
<li>Mongoose 是在 node.js 环境下对 mongodb 进行便捷操作的对象模型工具</li>
</ul>
<h3 id="2-安装"><a href="#2-安装" class="headerlink" title="2. 安装"></a>2. 安装</h3><ul>
<li>依赖 nodejs 和 mongodb</li>
<li>npm install mongoose –save</li>
<li>require(‘mongoose’)</li>
</ul>
<h3 id="3-connect-用于创建数据库连接"><a href="#3-connect-用于创建数据库连接" class="headerlink" title="3. connect 用于创建数据库连接"></a>3. connect 用于创建数据库连接</h3><ul>
<li>mongoose.connect(url(s), [options], [callback])<ul>
<li>//url(s):数据库地址,可以是多个,以<code>,</code>隔开</li>
<li>//options:可选,配置参数</li>
<li>//callback:可选,回调</li>
</ul>
</li>
<li>mongoose.connect(‘mongodb://用户名:密码@127.0.0.1:27017/数据库名称’)</li>
<li>连接多个 mongoose.connect(‘urlA,urlB,…’, {mongos : true })</li>
<li>mongoose.disconnect() 断开连接</li>
</ul>
<h3 id="4-Schema–Each-schema-maps-to-a-MongoDB-collection-and-defines-the-shape-of-the-documents-within-that-collection"><a href="#4-Schema–Each-schema-maps-to-a-MongoDB-collection-and-defines-the-shape-of-the-documents-within-that-collection" class="headerlink" title="4. Schema–Each schema maps to a MongoDB collection and defines the shape of the documents within that collection."></a>4. Schema–Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.</h3><ul>
<li>主要用于定义 MongoDB 中集合 Collection 里文档 document 的结构,</li>
<li>可以理解为 mongoose 对表结构的定义</li>
<li>(不仅仅可以定义文档的结构和属性,还可以定义文档的实例方法、静态模型方法、复合索引等),</li>
<li>每个 schema 会映射到 mongodb 中的一个 collection,</li>
<li>schema 不具备操作数据库的能力</li>
<li>String 字符串 Number 数字 Date 日期 Buffer 二进制 Boolean 布尔值 Mixed 混合类型 ObjectId 对象 ID Array 数组</li>
<li>如果需要在 Schema 定义后添加其他字段,可以使用 add()方法</li>
</ul>
<h3 id="5-Model–Models-are-fancy-constructors-compiled-from-Schema-definitions-An-instance-of-a-model-is-called-a-document"><a href="#5-Model–Models-are-fancy-constructors-compiled-from-Schema-definitions-An-instance-of-a-model-is-called-a-document" class="headerlink" title="5. Model–Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document."></a>5. Model–Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document.</h3><ul>
<li>是由 Schema 编译而成的假想(fancy)构造器,具有抽象属性和行为。</li>
<li>Model 的每一个实例(instance)就是一个 document,document 可以保存到数据库和对数据库进行操作。</li>
<li>简单说就是 model 是由 schema 生成的模型,可以对数据库的操作。</li>
<li>实例化文档 document,通过对原型 Model 使用 new 方法,实例化出文档 document 对象</li>
<li>文档保存。必须通过 save()方法,才能将创建的文档保存到数据库的集合中</li>
<li>实例方法和静态方法.区别在于,静态方法是给 model 添加方法,实例方法是给 document 添加方法</li>
<li>Mongoose 会将集合名称设置为模型名称的小写版。如果名称的最后一个字符是字母,则会变成复数;如果名称的最后一个字符是数字,则不变</li>
</ul>
<h3 id="6-Documents–Each-document-is-an-instance-of-its-Model"><a href="#6-Documents–Each-document-is-an-instance-of-its-Model" class="headerlink" title="6. Documents–Each document is an instance of its Model."></a>6. Documents–Each document is an instance of its Model.</h3><h3 id="7-文档新增"><a href="#7-文档新增" class="headerlink" title="7. 文档新增"></a>7. 文档新增</h3><ul>
<li>实例化 model,然后 save()</li>
<li>使用模型 model 的 create()方法,Model.create(doc(s), [callback])</li>
<li>最后一种是模型 model 的 insertMany()方法,Model.insertMany(doc(s), [options], [callback])</li>
</ul>
<h3 id="8-文档查询"><a href="#8-文档查询" class="headerlink" title="8. 文档查询"></a>8. 文档查询</h3><ul>
<li>find()<ul>
<li>第一个参数表示查询条件,第二个参数用于控制返回的字段,第三个参数用于配置查询参数,第四个参数是回调函数</li>
<li>Model.find(conditions, [projection], [options], [callback])</li>
</ul>
</li>
<li>findById()<ul>
<li>Model.findById(id, [projection], [options], [callback])</li>
</ul>
</li>
<li>findOne()<ul>
<li>该方法返回查找到的所有实例的第一个</li>
</ul>
</li>
<li>文档查询中,常用的查询条件如下 (Query and Projection Operators)<ul>
<li>$or 或关系</li>
<li>$nor 或关系取反</li>
<li>$gt 大于</li>
<li>$gte 大于等于</li>
<li>$lt 小于</li>
<li>$lte 小于等于</li>
<li>$ne 不等于</li>
<li>$in 在多个值范围内</li>
<li>$nin 不在多个值范围内</li>
<li>$all 匹配数组中多个值</li>
<li>$regex 正则,用于模糊查询</li>
<li>$size 匹配数组大小</li>
<li>$maxDistance 范围查询,距离(基于 LBS)</li>
<li>$mod 取模运算</li>
<li>$near 邻域查询,查询附近的位置(基于 LBS)</li>
<li>$exists 字段是否存在</li>
<li>$elemMatch 匹配内数组内的元素</li>
<li>$within 范围查询(基于 LBS)</li>
<li>$box 范围查询,矩形范围(基于 LBS)</li>
<li>$center 范围醒询,圆形范围(基于 LBS)</li>
<li>$centerSphere 范围查询,球形范围(基于 LBS)</li>
<li>$slice 查询字段集合中的元素(比如从第几个之后,第 N 到第 M 个元素</li>
</ul>
</li>
</ul>
<h3 id="9-文档更新"><a href="#9-文档更新" class="headerlink" title="9. 文档更新"></a>9. 文档更新</h3><ul>
<li>Model.update(conditions, doc, [options], [callback])<ul>
<li>第一个参数 conditions 为查询条件,第二个参数 doc 为需要修改的数据,第三个参数 options 为控制选项,第四个参数是回调函数</li>
<li>options 有如下选项<ul>
<li>safe (boolean): 默认为 true。安全模式。</li>
<li>upsert (boolean): 默认为 false。如果不存在则创建新记录。</li>
<li>multi (boolean): 默认为 false。是否更新多个查询记录。</li>
<li>runValidators: 如果值为 true,执行 Validation 验证。</li>
<li>setDefaultsOnInsert: 如果 upsert 选项为 true,在新建时插入文档定义的默认值。</li>
<li>strict (boolean): 以 strict 模式进行更新。</li>
<li>overwrite (boolean): 默认为 false。禁用 update-only 模式,允许覆盖记录。</li>
</ul>
</li>
</ul>
</li>
<li>updateMany()与 update()方法唯一的区别就是默认更新多个文档,即使设置{multi:false}也无法只更新第一个文档</li>
<li>如果需要更新的操作比较复杂,可以使用 find()+save()方法来处理</li>
<li>updateOne()方法只能更新找到的第一条数据,即使设置{multi:true}也无法同时更新多个文档</li>
<li>findOne() + save()</li>
<li>Model.findOneAndUpdate([conditions], [update], [options], [callback])</li>
<li>Model.findByIdAndUpdate([conditions], [update], [options], [callback])</li>
<li>操作符 <a target="_blank" rel="noopener" href="https://docs.mongodb.com/v2.4/reference/operator/update/">Update Operators</a></li>
</ul>
<h3 id="10-文档删除"><a href="#10-文档删除" class="headerlink" title="10. 文档删除"></a>10. 文档删除</h3><ul>
<li>remove<ul>
<li>model.remove(conditions, [callback])</li>
<li>document.remove([callback])</li>
</ul>
</li>
<li>Model.findOneAndRemove(conditions, [options], [callback])</li>
<li>Model.findByIdAndRemove(id, [options], [callback])</li>
</ul>
<h3 id="11-查询后处理"><a href="#11-查询后处理" class="headerlink" title="11. 查询后处理"></a>11. 查询后处理</h3><ul>
<li>sort 排序 按某字段排序</li>
<li>skip 跳过 做任何操作前跳过若干</li>
<li>limit 限制 规定最大返回数量</li>
<li>select 显示字段 规定显示的字段</li>
<li>count 计数 计数查询结果</li>
<li>distinct 去重 统计某字段值的情况</li>
<li>exect 执行 执行最终查询</li>
</ul>
<h3 id="12-文档验证"><a href="#12-文档验证" class="headerlink" title="12. 文档验证"></a>12. 文档验证</h3><ul>
<li>Validation is defined in the SchemaType 定义在 schema 中</li>
<li>Validation is middleware. Mongoose registers validation as a pre(‘save’) hook on every schema by default.中间件,默认注册了 pre(‘save’) 钩子</li>
<li>You can manually run validation using doc.validate(callback) or doc.validateSync() 可手动运行</li>
<li>Validators are not run on undefined values. The only exception is the required validator. 未定义值不会校验</li>
<li>Validation is asynchronously recursive; when you call Model#save, sub-document validation is executed as well. If an error occurs, your Model#save callback receives it 嵌套异步执行</li>
<li>Validation is customizable 自定义</li>
<li>规则<ul>
<li>required: 数据必须填写</li>
<li>default: 默认值</li>
<li>validate: 自定义匹配</li>
<li>min: 最小值(只适用于数字)</li>
<li>max: 最大值(只适用于数字)</li>
<li>match: 正则匹配(只适用于字符串)</li>
<li>enum: 枚举匹配(只适用于字符串)</li>
</ul>
</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2018/12/26/mongoose/" data-id="ckmau8ydt000w6nre2co67rxp" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mongo/" rel="tag">mongo</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mongoose/" rel="tag">mongoose</a></li></ul>
</footer>
</div>
</article>
<article id="post-linux-node" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2018/11/29/linux-node/" class="article-date">
<time datetime="2018-11-29T09:10:34.000Z" itemprop="datePublished">2018-11-29</time>
</a>
<div class="article-category">
<a class="article-category-link" href="/categories/web/">web</a>
</div>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="article-title" href="/2018/11/29/linux-node/">在linux从0搭建node环境</a>
</h1>
</header>
<div class="article-entry" itemprop="articleBody">
<h3 id="1-下载压缩包(二进制,非源码)"><a href="#1-下载压缩包(二进制,非源码)" class="headerlink" title="1. 下载压缩包(二进制,非源码)"></a>1. 下载压缩包(二进制,非源码)</h3><ul>
<li>选择需要的版本,平台一般为 linux-x64(运维提供的系统版本)</li>
<li>选择压缩格式 一般选择 tar.gz (包较大,但解压方便)</li>
<li>node-v8.10.0-linux-x64.tar.gz (17960765kb)</li>
<li>命令 wget <a target="_blank" rel="noopener" href="https://nodejs.org/download/release/v8.10.0/node-v8.10.0-linux-x64.tar.gz">https://nodejs.org/download/release/v8.10.0/node-v8.10.0-linux-x64.tar.gz</a></li>
</ul>
<h3 id="2-解压缩即安装"><a href="#2-解压缩即安装" class="headerlink" title="2. 解压缩即安装"></a>2. 解压缩即安装</h3><ul>
<li>选择解压目录</li>
<li>命令 tar -xvf node-v8.10.0-linux-x64.tar.gz</li>
<li>解压到当前目录,也可改变目标目录 -C</li>
</ul>
<h3 id="3-全局使用"><a href="#3-全局使用" class="headerlink" title="3. 全局使用"></a>3. 全局使用</h3><ul>
<li>想在全局环境使用 node 命令及 npm 全局安装的包</li>
<li>需要向系统声明 node 可执行文件及全局包的位置 →PATH 环境变量</li>
<li>/usr/bin/ 、/usr/local/bin。。。</li>
<li>方法:建立软链、直接修改环境变量</li>
<li>软链:命令 ln -s /usr/local/node-v8.10.0-linux-x64/bin/node /usr/bin/node 同理建立 npm pm2 的,pm2 可先用 npm 安装</li>
<li>修改变量:export PATH=/usr/local/node-v8.10.0-linux-x64/bin:$PATH (针对当前用户)</li>
<li>多种途径:/etc/profile、/etc/profile.d、/home/dev-user/.bashrc 等</li>
<li>注意:由于 npm 等包经常需要读写权限,还需要赋予 node 所在位置的读写权限给当前用户(修改属主也可)。</li>
<li>sudo chown dev-user:dev-user /usr/local/node-v8.10.0-linux-x64/ -R</li>
</ul>
</div>
<footer class="article-footer">
<a data-url="https://dontcallmilanac.github.io/2018/11/29/linux-node/" data-id="ckmau8ydl000i6nreelyb449a" class="article-share-link">Share</a>
<ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/linux/" rel="tag">linux</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>
</footer>
</div>
</article>
<nav id="page-nav">
<span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="extend next" rel="next" href="/page/2/">Next &raquo;</a>
</nav>
</section>
<aside id="sidebar">
<div class="widget-wrap">
<h3 class="widget-title">Categories</h3>
<div class="widget">
<ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/linux/">linux</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/web/">web</a></li></ul>
</div>
</div>
<div class="widget-wrap">
<h3 class="widget-title">Tags</h3>
<div class="widget">