2007年8月27日 星期一

AOP for jQuery

就在寫 jQuery 1.1.4 那篇介紹文的同時, 逛了一下 jQuery plugins , 看到了一個很有意思的專案.
jQuery AOP , 看起來是一個新的專案,作者於 2007/08/17 上傳第一個 release 檔案.

aspect-oriented programming (AOP) 在 Java 中有幾個流行的 AOP 實作, AspectJ , AspectWerkz JBossAOP, 所以有關 AOP 的介紹, 請看上面四個 Link, 不在此重覆說明.

而 jQuery AOP 則是實作了 before / after / around 三個 advice, 雖然名為 jQuery AOP, 其實並未使用到 jQuery 的任何特性及功能, 所以即使您沒有使用 jQuery , 依然可以小改一下 code 來使用哦, 所以一定要堆的啦.

##CONTINUE##
我們可以很容易的利用 javascript 的 Function.apply() 來 hook function 或 object(Blogger Hack Tip#1) , 所以實作起來相當的輕巧, 只有 943 bytes.

舉一個實例:
任何程式語言, 在程式寫作過程中, 我們少不了要 Log , 然而 Log 的動作和程式本身實際的業務邏輯無關, 若是為每一個業務操作的 function / method 前後都加上 Logger.log('message'), 對於程式本身而言.. 太過於難看(bad smell).
所以這時我們可以藉由 Dynamic proxy 或 AOP framework 來改善這個 bad smell.

使用 jQuery AOP 在 javascript 中使用 after / before / around advices 變的很簡單:

例1 對 native object 切入:

jQuery.aop.before( {target: String, method: 'replace'},
function(regex, newString) {
alert("About to replace string '" + this + "' with '" + newString + "' using regEx '" + regex + "'");
}
);
"Hello World".replace("Hello", "Hello jQuery");


例2 對 global function 切入:

function testEcho ( arg) {
alert('testEcho: ' + arg);
}
jQuery.aop.before( {target: window, method: 'testEcho'},
function(arg) {
alert("About to testEcho arguments is " + arg);
}
);


例3 對 instance object 切入:

var TestObj = function (name) {
this.name = name;
};
TestObj.prototype.hello = function (arg) {
alert(this.name + ':' + arg);
};
var rack = new TestObj('rack');
jQuery.aop.before( {target: rack, method: 'hello'},
function(arg) {
alert("before "+ this.name +" say " + arg);
}
);
rack.hello('hello');


其它各位依此類堆.... 有了 jQuery AOP , javascript 也能寫的很優雅嘍.
(都已經 Hook Blogger了, 之前怎麼沒想到順便弄一個 plugin , 唉~~ sense 不足.. 被搶頭香了 :D )

3 則留言:

Jace Ju 提到...

阿土伯,最近你怎麼老是被人搶頭香呀? XD

不過看到你寫這篇,我突然有個好主意...先保密一下好了,免得頭香換被你搶去。 :P

Unknown 提到...

Dear jaceju:
呵呵.. 是呀~~只要有心, 人人可以插頭香!
很樂於見到大家一起一篇又一篇的技術文章討論.. 這樣的感覺很好, 期待你的秘密作品嘍...

薛共和 提到...

你也玩這些東西嗎?http://rd-program.blogspot.com 歡迎你參觀我的blog,也許可以交流交流