JavaScript 響應式編程模式有點類似 WebForm 中的事件驅動模式(傳相應的處理函數給委托,通過事件來觸發來進行相關的處理),在 AngularJs 2.x 框架中,應用了 RxJS API,具體可以參考 AngularJs 官網。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript"> //定義功能類似C#中的委托的函數 function showId(func, param) { if (func) { func(param); } } //顯示標簽的id(響應式編程方式,類似WebForm中的事件機制) function myClick(t) { showId(function (x) { alert(x); }, t); } </script> </head> <body> <div onclick="myClick(this.id)" id="myDiv">Click to show id</div> </body> </html>
js中把字符串轉成函數
<html> <head> <!--js中把字符串轉成函數--> <meta charset="utf-8" /> </head> <body> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ //函數體字符串 var jsStr = 'function checkLength(){ var v = $(this).val(); if(v.length > 3){ alert(v+": 長度大於 3"); } }'; jsStr += ' function checkType(){ var re = /[\+]/; var v = $(this).val(); if(re.test(v)){ alert(v+": 包含: \+"); } }'; //創建一個<script>標簽 var scriptTag = document.createElement("script"); scriptTag.innerHTML = jsStr; //把新建的<script>標簽添加到<head>標簽中 document.getElementsByTagName("head")[0].appendChild(scriptTag); //為input標簽綁定事件 $("#name").bind("blur", checkLength); $("#name").bind("blur", checkType); }); </script> <input id="name" type="text" /> </body> </html>
RxJS參考資源:
https://github.com/Reactive-Extensions/RxJS
http://bbs.csdn.net/topics/380250714
並發編程參考書籍:
《C#並發編程經典實例》 Stephen Cleary 著 相銀初 譯
