為其他物件提供一個代理,以控制對該物件的存取。代理幾乎可以代表任何東西:檔案、資源、記憶體物件、難以複製的大型物件、遠端服務等。
// 真實主題:美女
var Girl = function(name) { this.name = name; };
// 真實物件:dudu 想送花
var Dudu = function(girl) {
this.girl = girl;
this.sendGift = function(gift) {
alert("Hi " + girl.name + ", dudu送你一個禮物:" + gift);
};
};
// 代理:大叔幫忙送
var ProxyTom = function(girl) {
this.girl = girl;
this.sendGift = function(gift) {
(new Dudu(girl)).sendGift(gift); // 轉發給真實物件
};
};
// 使用
var proxy = new ProxyTom(new Girl("酸奶小妹"));
proxy.sendGift("999朵玫瑰");
需求:清單含多個視頻,點擊連結/全選 → 載入視頻詳情並顯示 Play 按鈕 → 點擊 Play 播放視頻。使用代理模式統一管理網路請求與 UI 更新。
var $ = function(id) { return document.getElementById(id); };
var http = {
makeRequest: function(ids, callback) {
var url = 'https://query.yahooapis.com/v1/public/yql?q=',
sql = 'select * from music.video.id where ids IN ("%ID%")',
format = "format=json",
handler = "callback=" + callback,
script = document.createElement('script');
sql = sql.replace('%ID%', ids.join('","'));
sql = encodeURIComponent(sql);
url += sql + '&' + format + '&' + handler;
script.src = url;
document.body.appendChild(script);
}
};
var proxy = {
ids: [], delay: 50, timeout: null, callback: null, context: null,
makeRequest: function(id, callback, context) {
this.ids.push(id); // 加入佇列
this.callback = callback;
this.context = context;
if (!this.timeout) { // 去抖:50ms 內多次呼叫合併為一次請求
this.timeout = setTimeout(function() { proxy.flush(); }, this.delay);
}
},
flush: function() {
http.makeRequest(this.ids, 'proxy.handler'); // 發送合併請求
this.timeout = null;
this.ids = [];
},
handler: function(data) { // YQL 回調入口
var videos = data.query.results.Video;
if (parseInt(data.query.count, 10) === 1) {
proxy.callback.call(proxy.context, videos);
} else {
for (var i = 0, max = videos.length; i < max; i++) {
proxy.callback.call(proxy.context, videos[i]);
}
}
}
};
var videos = {
getPlayer: function(id) { /* 回傳 Flash Player HTML 字串 */ },
updateList: function(data) { // 渲染視頻詳情 + Play 連結
var html = '<img src="' + data.Image[0].url + '" width="50" />';
html += '<h2>' + data.title + '</h2>';
html += '<p>' + data.copyrightYear + ', ' + data.label + '</p>';
html += '<p><a class="play" href="...">» play</a></p>';
var div = document.createElement('div');
div.id = "info" + data.id;
div.innerHTML = html;
$('v' + data.id).appendChild(div);
},
play: function(id) { // 代理播放邏輯
if ($('info' + id)) {
$('info' + id).innerHTML = this.getPlayer(id);
} else {
proxy.makeRequest(id, this.updateList, this); // 透過代理請求資料
}
}
};
// 全選/反選
$('toggle-all').onclick = function() {
var inputs = $('vids').getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) inputs[i].checked = !inputs[i].checked;
};
// 連結點擊 → 代理請求資料
var links = $('vids').getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
var id = this.href.split('--')[1];
proxy.makeRequest(id, videos.updateList, videos);
return false; // 阻止跳轉
};
}
// Play 連結點擊 → 代理播放
// (需事件委託,動態新增的 .play 連結)
document.body.onclick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.className === 'play') {
var id = target.href.split('--')[1];
videos.play(id);
return false;
}
};
proxy 控制對 http.makeRequest 的存取,外部無法直接呼叫。makeRequest 佇列 + setTimeout 去抖,合併短時間內多個請求,減少網路開銷。proxy 代表遠端 YQL 服務,處理 JSONP 回調細節。videos.play 先檢查本地是否已有資料(info{id} 存在),有則直接播放,無則透過代理請求。代理模式不只是「轉發呼叫」,其精髓在於控制存取:決定何時、如何、是否轉發給真實物件。本案例展示了緩衝合併請求、快取檢查、統一錯誤處理等多重代理職責,是前端架構中解耦網路層與 UI 層的經典範式。