ie421.NET

面对技术,你别无选择,.NET世界是如此精彩,而我们要做的就是:Thinking More

博客园 首页 新随笔 联系 订阅 管理
作者 tinchen 於 AJAX, JavaScript - 2007-04-08

隨 著 web 2.0 的風潮,在 ajax 技術的廣泛應用下,javascript 在開發上被使用的機會也更多了,我們常利用 javascript 來處理 client 端 UI 的互動處理,實務上免不了需要用 javascript 動態的產生 html elemet 作顯示,目前常用的方法有兩種,一種是在 script 中以字串的方法組合出所需的 html code,然後以設定 innerHTML 的方式指定給某個 html elemet:


  1. var html = "<table id='" + theId + "' border='0'>";
  2. html += "<tr><td>" + title + "</td></tr>";
  3.  
  4. // ...
  5.  
  6. $('theDiv').innerHTML = html;

另一種則是以 document.createElement(..) 的方式以 OO 的方式來建立所需的 html elemet:

  1. var container= document.createElement('div');
  2. container.style.position = "absolute";
  3. container.className = "portal-container";
  4. container.style.fontSize = 12;
  5. ...
  6. document.body.appendChild(container);
  7. ...

當然我們也常會混著一起使用,但這兩種方法都有一樣的缺點,就是日後維護會很辛苦,而且擴充的彈性很小,如果你開發的是一個 frmework 或可共用的 UI component,其他的開發人員想客製或擴充都會很痛苦,最主要的原因就是我們將太多 UI 的 html code 混雜到 script code 中了,想想看在 server side 的開發經驗中,我們是怎麼處理這種問題的?
將 model 和 view 分開,沒錯就是這個概念,這裡介紹一個 JavaScript templates engine,它可以有效的解決這個問題,看一個例子:

  1. <html>
  2. <head>
  3. <script language="javascript" xsrc="trimpath/template.js"></script>
  4. ...
  5. </head>
  6.  
  7. <textarea id="cart.jst" style="display:none;">
  8. <table id='${tableId}' border='0'>
  9. <tr>
  10. <td>
  11. Hello ${customer.first} ${customer.last}.<br/>
  12. Your shopping cart has ${itemCount} item(s):
  13. </td>
  14. </tr>
  15. </table>
  16. </textarea>
  17. </html>

上面我們將 template.js include 進來,以便在 script 中使用,再來定義了一個 id 為 cart.jst 的 textarea,注意我們將它的 CSS 屬性 display 設定為 none,裡面則是標準 html code 加上 templates engine 能辨識的變數名稱。在 script 中我們可以這麼使用:

  1. var model = {
  2. tableId : totalTableId++,
  3. customer : getCustomerById(id),
  4. itemCount : itemCount
  5. }
  6.  
  7. $('theDiv').innerHTML = TrimPath.processDOMTemplate("cart.jst", model);

這裡我們將要丟入 templates engine 中的資料作組合,然後使用 TrimPath.processDOMTemplate("template id", 資料) 的方式讓 templates engine 幫我們作『融合』產出我們要的 html code。

就像是 FreeMarker,Velocity,Smarty 這些 Templates engine 一樣,TrimPath JavaScript templates engine 也提供了 if,for each,macro 等功能,值得多加使用讓 script 的維護不再是惡夢。

posted on 2008-08-19 15:07  ie421  阅读(503)  评论(0编辑  收藏  举报