DIV CSS 佈局教程網

Dess 中的多路委託(SDelegate)實作解析
編輯:關於JavaScript     

這是一個多路委託(multicast delegate)的實作,讓多個函式可以串成一條鏈,依序被呼叫,並支援中途移除。

var SDelegate = function(f, b, c) {
if (b) {
this.asFunction_ = function() { return f.apply(b, arguments); };
} else {
this.asFunction_ = function() { return f.apply(this, arguments); };
}
this.method_   = f;
this.binding_  = b;
this.continus  = c;   // 下一個委託(注意原字的拼字)
}

// 把整條委託鏈合成一個可呼叫的函式
SDelegate.composite = function(d) {
if (d.continus) {
var con = d.continus.composited_ = SDelegate.composite(d.continus);
var method = d.asFunction_;
return function() {
con.apply(this, arguments);      // 先呼叫鏈的後段
return method.apply(this, arguments);
};
} else {
return d.asFunction_;
}
}

SDelegate.prototype.call = function() {
if (!this.composited_) this.composited_ = SDelegate.composite(this);
return this.composited_.apply(arguments[0], Array.prototype.slice.call(arguments, 1));
}

// 依測試條件從鏈中移除節點
SDelegate.prototype.remove = function() {
var removeP = function(parent, item, test, data) {
if (!item) return;
parent.composited_ = item.composited_ = null;   // 清掉合成快取
if (test(item, data)) {
parent.continus = item.continus;               // 跳過被移除的節點
removeP(parent, item.continus, test, data);
} else {
removeP(item, item.continus, test, data);
}
};
return function(test, data) {
var p = this;
if (test(this, data)) { p = this.continus; }
removeP(p, p.continus, test, data);
p.composited_ = null;
return p;
};
}();

SDelegate.prototype.append = function(f, b) {
return new SDelegate(f, b, this);
}

幾個設計細節值得注意:composite() 用遞迴把整條鏈折疊成單一函式,並把結果快取在 composited_ 上避免重複運算;remove() 在改動鏈結構時必須一併把 composited_ 設為 null,快取才不會失效;call() 的第一個參數作為 this,其餘往後傳。

這套 SDelegate 的使用方式確實比較特殊——很多操作都要重新賦值,因為它是不可變鏈式結構(每次 append 都回傳新節點)。在 Dess 這個框架裡,它主要用在 DOM 事件派發等特定場合,而不是當成通用工具。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved