YUI3 PR1試用

 Thu, 30 Oct 2008 18:03:23 +0800

前幾天去聽Yahoo的前端工程師講YUI3跟一些Yahoo open出來的有趣東西。

YUI比之前改進不少,尤其跟JQuery學了一些東西,試寫了一個選單的效果:

<html>
<style>
    .cls1 {background-color: white}
    .cls2 {background-color: black;color:white;cursor:pointer}
</style>
<script src="build/yui/yui-min.js"></script>
<body>
<div  class="cls1" style="border:solid 1px black;width:120px">test1</div>
<div  class="cls1" style="border:solid 1px black;width:120px">test2</div>
<div  class="cls1" style="border:solid 1px black;width:120px">test3</div>
<div  class="cls1" style="border:solid 1px black;width:120px">test4</div>
<div  class="cls1" style="border:solid 1px black;width:120px">test5</div>
<script>
YUI().use("node",function(Y){
    var obj = Y.all(".cls1");
    obj.on("mouseover",function(e){e.target.toggleClass("cls2");});
    obj.on("mouseout",function(e){e.target.toggleClass("cls2");});
});
</script>
</body>
</html>

這樣就可以做出一個反白的選單效果:

test for test341

使用YUI3的style有一個好處,就是所有的code會寫在一個callback函數裡面,這樣比較不會污染到global space。其他的好處,就慢慢試囉。

(從範例看起來,呼叫YUI.use()後,YUI會負責把使用到的模組動態載入,然後呼叫使用者定義的callback函數,並且把YUI物件的實例用參數傳給這個callback使用。用這個方式,可以把對global scope的改變縮到最小吧?另外,YUI3也加了不少wrap物件,例如用all()傳回的nodelist,使用get()傳回的node,或是上例event handler函數中的參數e都是。這樣可以讓操作一致化,也更直覺,這個方式也很像JQuery。不過我覺得JQuery的cascade很好用,使用起來也很直覺,可惜YUI3沒這樣支援,不過也許他是要求嚴謹,怕濫用cascade??)