使用jquery-tmpl使JavaScript与HTML分离

背景:由于对JavaScript字符串拼接JavaScript变量产生了反感,也想用用JavaScript模板库,看了几个,由于时间原因选择了jQuery.tmpl.js,因为Visual Studio 对其的语法高亮支持。

0. 下载 jQuery templates plugin

jQuery Templates plugin vBeta1.0.0

1. 准备工作

1.1 JSON数据

JSON数据在这里类似于“接口文档”,明确哪些数据必须对应到HTML的哪个位置,还有一些作为判断条件的字段,可以根据字段不同的值来显示不同的样式;这里采用一段经转换(JSON.parse(/*JSON String*/))好的数据

 1 var MockResponseFromServer = {

 2     code: '1', // '1'表示获取数据成功

 3     data: [

 4     {

 5         productid: "001",

 6         productname: "Lumia 930",

 7         productnumber: "GD1502001",

 8         productpic: "http://www.globalmediahk.com/uploads/magazine/15/3cc3ca3f-a403-42d9-a850-b9d08c88fd48.jpg",

 9         memberprice: 35,

10         price: 35,

11         quantity: 0

12     },

13     {

14         productid: "002",

15         productname: "Lumia 520",

16         productnumber: "GD1502002",

17         productpic: "http://blog.orange.pl/uploads/media/b/9/c/5/3/189d1cfd42952ad73b4d91c4700016151d0",

18         memberprice: 35,

19         price: 35,

20         quantity: 0

21     }],

22     msg: '成功'

23 };

1.2 HTML

HTML 转换为 x-jquery-tmpl,{{}} ,${} {{if}}具体语法请参见插件的示例文档,这些符号在Visual Studio 下有语法高亮

 1 <script id="productItemTmpl" type="text/x-jquery-tmpl">

 2  {{if quantity=== 0}}  3         <div class="gshow-box gshow-box-disabel">

 4  {{else}}  5             <div class="gshow-box">

 6  {{/if}}

 7                 <div class="gshow-box">

 8  {{if quantity === 0 }}  9                     <div class="disabelPanel"></div>

10  {{/if}}

11                     <a href="${productDetailUrl}" target="_blank">

12                         <img class="gshow-box-img lazy" data-original="${productpic}" alt="${productname}">

13                     </a>

14                     <a class="g-title" href="${productDetailUrl}" target="_blank">${productname}</a>

15                     <div class="clearfix">

16                         <label class="fl">

17 ${memberprice} 18                             <span class="discount">${price}</span>

19                         </label>

20                         <span class="fr">

21 <span class="color-red">${quantity}</span>件

22                         </span>

23                     </div>

24                 </div>

25     </script>

 

2. 编写HTML

 1 <body>

 2     <div class="container">

 3         <h1>产品列表</h1>

 4         <hr />

 5         <div id="ProductContainer" class="qg-gshow-temp clearfix">

 6         </div>

 7     </div>

 8     <script src="jquery-1.7.2.js"></script>

 9     <script src="jquery.lazyload.js"></script>

10     <script src="jquery.tmpl.js"></script>

11     <script src="IAPP.js"></script>

12 </body>

3. JavaScript

 1 (function ($) {

 2     var IAPP = {};

 3 

 4     IAPP.ProductTmpl = 'ProductTmpl';

 5     IAPP.$ProductContainer = $('#ProductContainer');

 6 

 7     function setLazyloadImg() {

 8         /// <summary>

 9         /// 设置图片延迟加载

10         /// </summary>

11         $('img.lazy').lazyload({

12             effect: 'fadeIn'

13             , failure_limit: 10

14             , threshold: 50

15             , event: 'scroll'

16         });

17     }

18 

19     IAPP.loadDataByAjax = function (handler) {

20         /// <summary>

21         /// AJAX请求产品JSON数据

22         /// </summary>

23         /// <param name="handler">success回调处理函数</param>

24         $.ajax({

25             type: 'POST',

26             url: 'url/getdata.ashx',

27             data: { cmd: 'productlist' },

28             dataType: 'json',

29             success: handler,

30             error: function () {

31                 // error handler

32                 console && console.info('error:some message');

33                 // 当AJAX请求发生错误时,用模拟数据测试模板

34                 handler(MockResponseFromServer);

35             }

36         });

37     };

38 

39     IAPP.loadDataByAjaxHandler = function (result) {

40         /// <summary>

41         /// 回调函数

42         /// </summary>

43         /// <param name="result">response from server</param>

44         var l = 0, // 用于保存产品的个数

45          data, // 产品列表(Array)

46          entityObj; // 用于保存产品实体对象

47 

48         if (!result) { throw 'no response from server'; }

49 

50         if (result.code && result.code === '1') {

51             result.data && (data = result.data);

52             if (data && data.length) {

53                 l = data.length;

54                 while (l--) {

55                     entityObj = data.shift();

56                     // 产品链接

57                     entityObj['productDetailUrl'] = './product.aspx?pid=' + entityObj.productid;

58 

59  $.tmpl(IAPP.ProductTmpl, entityObj).appendTo(IAPP.$ProductContainer); 60                 }

61 

62                 setLazyloadImg(); // 延迟加载

63             }

64         } else {

65             console && console.error(result.msg);

66         }

67     };

68 

69     ({

70         initTmpl: function () {

71             /// <summary>

72             /// 初始化jQuery.tmpl

73             /// </summary>

74 

75             // $.template(name/*模板名称*/,tmpl/*模板字符串*/)

76             // 说明:使用此方式可以根据模板名访问模板以达到复用模板

77             $.template(IAPP.ProductTmpl, $('#productItemTmpl').html()); 78         },

79         initData: function () {

80             /// <summary>

81             /// 获取数据

82             /// </summary>

83             IAPP.loadDataByAjax(IAPP.loadDataByAjaxHandler);

84         }, init: function () {

85             /// <summary>

86             /// 所有的初始化动作

87             /// </summary>

88             this.initTmpl();

89             this.initData();

90         }

91     }).init();

92 

93 }(jQuery));

 

你可能感兴趣的:(JavaScript)