[jQuery Plugin] jBind

分類: jQuery|技術分享 作者: abu

18 六月 2009

自從用了Smarty之後,讓我完全無法脫離那種 --> 輕易控制樣板上的資料呈現方式。

偶然看到原來javascript也有樣板系統,既然有類似的樣板概念,就來試用看看吧。

javascript樣板有很多款,這次選定的是一款jQuery Plugin → 『jBind』。

使用方式:

載入 jQuery 及 jBind

<script src="js/jquery.js" type="text/javascript"></script>
 
<script src="js/jquery.jbind.js" type="text/javascript"></script>

html部份

<div style="display:none;">
<div class="content">
<!--data-->
<div class="viewBlock">
#{id}
 
<strong>{name} {family}</strong>,
 
<em>{education}</em>,
 
{history}
<!--birthdate-->
<div class="age">
{month} {date} {year}</div>
<!--birthdate-->
<!--Publications-->
<div class="role">
{book} ({year})</div>
<!--Publications--></div>
<!--data--></div>
</div>

最外層第一個div(id=template),是我們設定的樣板樣式,最外層第二個div(id=show),是用來輸出結果。

javascript部份

$(function(){
 
var template = $('#template').html();
var data = 	[
{
id:41,
name:'Scott',
family:'Adams',
education:'Economics',
history:"Scott Adams was born in Windham, New York in 1957 and received his Bachelor's degree in Economics from Hartwick College in 1979. He also studied economics and management for his 1986 MBA from the Haas School of Business at the University of California, Berkeley.",
birthdate: {month:'June',date:8,year:1957},
Publications: [{book:'The Dilbert Future',year:1997},{book:'The Dilbert Principle',year:1996}]
},
{
id:59,
name:'Jack',
family:'Welch',
education:'Chemical Engineering',
history:'Jack Welch was born in Peabody, Massachusetts to John, a Boston &amp; Maine Railroad conductor, and Grace, a housewife. Welch attended Salem High School and later the University of Massachusetts Amherst, graduating in 1957 with a Bachelor of Science degree in chemical engineering. While at UMass he was a member of the Alpha chapter of the Phi Sigma Kappa fraternity.',
birthdate: {month:'November',date:19,year:1935},
Publications: [{book:'Winning',year:2005}]
}
];
var node = $(template).bindTo(data);
$(node).appendTo('#show');
 
});

樣板對應javascript資料的方式,有比較簡單的兩個大原則
1.資料根區塊,需用註解符號包起來。
2.資料內,若是陣列型態,需使用該陣列變數名稱作為註解符號,將資料包起來,例如birthdate為一陣列,則在希望加上birthdate內容的部份,頭尾補上,在區塊內,左右大括號{}內直接填birthdate的變數key值即可顯示資料。

另外還有一些比較高級的應用方式,可直接參考官網,有很詳細的sample,或是打包回家慢慢研究。

因為之前沒用過javascript的樣板系統,覺得蠻新鮮的,目前沒有專案使用這樣的方式,未來若有機會再來嘗試看看。

我要留言

關於這裡

這個部落格分享了哇寶在電子商務領域的技術及資訊,希望能讓更多人一起為台灣的網路產業加油。