一個讓你的 Javascript 程式碼更容易模組化的 jQuery 插件

說明
Javascript 是一個事件驅動的程式語言. 因此往往程式碼會呈現巢狀式結構來使用回乎函數. 尤其在大型的前端網頁程式更容易發生. 然而這種程式寫法會讓你整個架構不夠彈性化.
jQuery Queue 插件可以讓你在函式範圍外增加此函式需要執行的回乎函數. 因此可以讓你的程式更容易有彈性的切割模組. 在大型的專案上, 這個插件可以說是不可或缺的!
Demo
- 按 這裡 檢視這個 demo
- 原始碼裡也包含了這個 demo 頁面
下載
- 從 Github 下載原始碼
需求
- jQuery 1.3.0+
支援瀏覽器
- Firefox 2.0+
- Internet Explorer 6+
- Safari 3+
- Opera 10.6+
- Chrome 8+
安裝
- 首先, 確定你使用了一個有效的 DOCTYPE
- 引用 JS 檔案
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript" src="path-to-file/jquery.queue.js"></script>
使用方法
語法
將函式放入一個 ‘列隊’ 之中
$.queue( 'add', 'queueName', function( arg1, arg2, arg3 ){ // do something here });
將函式從一個 ‘列隊’ 當中移除
var someFunction = function( arg1, arg2, arg3 ){ // some code } $.queue( 'remove', 'queueName', 'someFunction' );
執行 ‘列隊’ 當中的函式
$.queue( 'call', 'queueName', [ arg1, arg2, arg3 ]); // or $.queue( 'call', 'queueName', arg );
清除一個 ‘列隊’
$.queue( 'clear', 'queueName' );
範例程式碼
將儲存 ‘ajax call 資料’ 這個函式放入 ‘afterLoadPhotos’ 這個 ‘列隊’ 中. 在這裡我們使用了 $.secret 這個插件
// store data outside a ajax call $.queue( 'in', 'afterLoadPhotos', function( total, photos ){ // store( cache ) flickr photo data for later use $.secret( 'in', 'totalPhotos', total ). secret( 'in', 'photos', photos ); });
將 ‘產生 DOM 元素’ 這個函式放入 ‘afterLoadPhotos’ 這個 ‘列隊’ 中
// append photos to the dom using data 'outside' the ajax call $.queue( 'add', 'afterLoadPhotos', function( total, photos ){ var fragment = ''; $.each( photos, function( key, photo ){ fragment = fragment + '<li><a href="' + photo.imagePath + '">' + '<img scr="' + photo.thumb_path + '"/><span>' + photo.title + '</span></a></li>'; }); $( '#gallery' ).append( fragment ); });
執行 ‘afterLoadPhotos’ 列隊裡的函式
$.ajax({ type : 'get', url : '/flickr/photos', dataType : 'json', success : function( rsp ){ $.queue( 'call', 'afterLoadPhotos', [ rsp.total, rsp.photos ]); } });
使用這個插件我們不需要去定義 ajax call 裡面或是之後要執行什麼函式. 而且不只是 ajax call, 我們可以在整個應用程式中用這個插件來連結不同的類別和模組, 讓程式寫起來更加的彈性.
命名空間
$.queue
支援一層命名空間. 大型的應用程式常常需要將程式碼區分模組. 這時候命名空間就派上用場了.
範例程式碼:
// push a function to getPhotos queue under FLICKR module $.queue( 'add', 'FLICKR.afterGetPhotos', function( secret, extraParams ){ // do stuffs here }); // another function for searching images on google $.queue( 'add', 'GOOGLE.searchImage', function( args ){ // do other stuffs here }