最近在開發「按讚」功能,也就是類似對商品列表「按讚」或是「加入我的最愛」之類的功能。
(本篇不討論server side與database實作,僅討論client side的JavaScript)
按讚的對象是衣服,於是我先開份js檔:
1234567891011121314151617181920212223242526272829 // clothing.js// 我知道直接寫整串程式邏輯不好,一大團難以理解// 那我用function把各小功能包起來好了!// 先替按鈕加上click event,點了之後就送出ajax,// 把這個衣服加入我的最愛function setupToLikeButton(){// some codes$('.to_like').click(function(e){// some codes});}// 再來替已經按讚過的東西加上click event,// 點下去就送出ajax,從我的最愛移除function setupLikedButton(){// some codes$('.liked').click(function(e){// some codes});}// 大功告成,寫個「初始化」功能// 正式執行clothing.js這個偉大的模組function registerLikeButtonEvent(){setupToLikeButton();setupLikedButton();}
然後在所有需要「按讚」功能的頁面,加入這些程式碼:
12345678 <script src="/assets/js/jquery.js"></script><script src="/assets/js/clothing.js"></script><script type="text/javascript">$(document).ready(function(){registerLikeButtonEvent();});</script>
寫完之後,再看了一眼,一股涼意上心頭,覺得這些程式碼真的很可悲。
- 這只是把一串js code,用function隨便包一包、把功能隨便分開而已
- 在所有需要「按讚功能」的頁面加上一行registerLikeButtonEvent(),感覺不是模組化(一點也不物件導向),依然停留在procedural programming(這邊執行一串code、再跳過去執行那邊一串code,有bug的時候光tracing code就累死人)
- setupToLikeButton跟setupLikedButton可能會被誤用。應該禁止在registerLikeButtonEvent以外的地方執行(有點像private method)
- 多了setupToLikeButton、setupLikedButton、registerLikeButtonEvent三個global function,感覺就是很不爽
我對這串code很不滿意、覺得應該有更好的pattern。
立馬上網買三本書
- JavaScript 設計模式
- JavaScript大全(第六版)
- JavaScript:優良部分
其中「JavaScript 設計模式」果然是開卷有益。下面就是應用Module Pattern之後的寫法。
12345678910111213141516171819202122232425262728293031323334353637 // clothing.js// 先做出一個命名空間,讓變數名稱留在localvar LikeButtonModule;LikeButtonModule = (function(){// 提示使用者這個模組跟jQuery有相依性if (!window.jQuery) { throw new Error("LikeButtonModule requires jQuery") }// this line declares the module dependency and// gives the global variable a local reference.// 這行可以增進效能var $ = window.jQuery;var _setupToLikeButton = function(){// some codes$('.to_like').click(function(e){// some codes});}// end _setupToLikeButtonvar _setupLikedButton = function(){// some codes$('.liked').click(function(e){// some codes});}// end _setupLikedButton// the public API interfacereturn {initialize: function(){// initialization_setupToLikeButton();_setupLikedButton();}};}());
然後在所有需要「按讚」功能的頁面,加入這些程式碼:
12345678 <script src="/assets/js/jquery.js"></script><script src="/assets/js/clothing.js"></script><script type="text/javascript">$(document).ready(function(){LikeButtonModule.initialize();});</script>
各位覺得,有沒有比較模組化的感覺呢?
Q&A
Q1: 為什麼 setupToLikeButton函式前面多了底線?
只是命名慣例,提醒developer它有private性質。
Q2: 那setupToLikeButton為何會得到private性質?
因為它是function內的一個var,被限定在function的closure內,所以function以外的地方不能執行它。
Q3: LikeButtonModule只有提供一個initialize函式給別人使用?這什麼爛模組?
等到「按讚系統」需要的功能更複雜、更豐富時,可以在最後return的物件內定義模組公開API,到時這個pattern會看起來很完整很漂亮。
Q4: 我看到一個很怪的文法 (function(){}()); 請問它是什麼?
那是JavaScript的立即函式。簡單來說就是定義一個function然後馬上執行它。注意這個函式最後return一個物件,而這個物件也就是這個模組的公開API介面。
(Photo via Alison Christine, CC licensed)