之前写JS绑定数据曾经用过tmpl库,虽然功能比较强大但是感觉不是很轻量,对于相对简单的数据需求显得有些臃肿。而Ajax返回数据自己拼接html的方式又显得不够高端,因此今天看了一篇介绍artTemplate的文章,觉得还不错,便来体验试用一下。

选择artTemplate的原因有两个:

1.使用简单,轻量级。

2.性能比较高。

 

使用方式和tmpl类似,只需指定一个容器div和一个模板代码,JS执行一个方法就可以实现绑定。

性能的话根据 高性能JavaScript模板引擎原理解析 提到的低版本浏览器使用数组push的方式,现代浏览器使用+=的方式性能更高,觉得性能应该还不错,而且有报错提示。

 

于是便写了如下的Demo:

 

首先,先感受一下前台的数据展现:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>ArtTempTest</title>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
   1:  

   2:     <script src="JS/lib/template.js">

   1: </script>

   2:     <script src="JS/tempTest.js">

   1: </script>

   2: </head>

   3: <body>

   4:     <h2>ArtTemplate</h2>

   5:     <!--模板容器-->

   6:     <div id="container">

   7:     </div>

   8:     <!--使用script标签来当作模板标签,id为模板名-->

   9:     <!--数据对象名要与后台js定义的数据属性名称一致,如list-->

  10:     <script id="template" type="text/html">

  11:         <h3><%=title%></h3>

  12:         <ul id="mainContent">

  13:             <%for(i = 0; i < list.length; i ++) { %>

  14:         <li><dd>name: <span id="aName"></span> Category:<%=list[i].Category%> price:<%=list[i].Price%></dd></li>

  15:             <%}%>

  16:         </ul>

  17:     

</script>

</body>

</html>

值得注意的是绑定数据的时候需要自己写个for循环,放在<% %>里,有种写.net代码的风格和亲切感~

 

后台的js代码是核心的数据绑定部分:

$(document).ready(function () {

    // my test

    $.getJSON('api/products/mytest')

       .done(function (data) {

           //alert(JSON.stringify(data));

           //构造前台数据,构造数据的变量名可随意起,前台只对应tempdata的各个属性名。

           //所以再简单的json外面也要套一个tempdata,否则前台无法访问

           var tempData = [];

           tempData.list = data;

           tempData.title = "testTitle";

           var html = template.render('template', tempData);

           document.getElementById('container').innerHTML = html;

           //每行数据的事件绑定

           $("#mainContent").children("li").each(function (index) {//获取模板div的第一个孩子节点,注意层次关系,其间不要穿插其他元素

               var tTr = this;

               var selectedItem = tempData.list[index];//获取当前行数据对象,暂时使用数据索引方式访问。

               //绑定事件

               var aButton = $(tTr).find("#aName");

               aButton.append("<a href='#'>" + selectedItem.Name + "</a>");

               aButton.click(function () {

                   alert(selectedItem.Name + "的Category是:" + selectedItem.Category);

               });

           });

       });

});

其中需要注意的地方均在注释中进行了说明。唯一的不方便之处就是对于每一行数据事件的支持以及获取当前行数据的方式,没有tmpl里简单,还需要自己指定数据源对象,通过索引的方式来访问。

 

最终的呈现效果如下:

 

 

 

 

 

P.S. 附上一段使用tmpl的代码示例:

function GetData() {

 

    //获取许愿墙数据

    $.get(ControllerPath + "Heart/GetAllHeart", {}, function (data) {

        $("#content_loading").hide();//fadeOut(100);

 

        var jsonData = eval("(" + data + ")");

        //alert(jsonData.table[1].title);

        $("#ItemList").empty();

        RenderTemplatefunction($("#ItemList"), $("#ItemTemplate"), jsonData.table);

 

        $("#ItemList").children("dd").each(function (index) {

 

            var tTr = this;

            var selectedItem = $.tmplItem(this);

 

            var tmp_title = $(tTr).find("#item_title");

            var tmp_person = $(tTr).find("#item_person");

            var tmp_date = $(tTr).find("#item_date");

            var btnTitle = $(tTr).find("#btnTitle");

 

            var bgNumber = "it" + Math.floor(Math.random() * 10 + 9) + ".jpg"; //1-10的随机数

            var bg = $(tTr).find(".bg");

            bg.css('background-image', "url('../Content/img/bg/" + bgNumber + "')");

 

            var getRandomColor = function () {

                return (function (m, s, c) {

                    return (c ? arguments.callee(m, s, c - 1) : '#') +

                        s[m.floor(m.random() * 16)]

                })(Math, '0123456789abcdef', 5)

            }

 

            var Color = getRandomColor();

            $(tTr).find("#item_title").css('color', Color.toString());

 

            //绑定数据

            tmp_title.html(selectedItem.data.title);

            tmp_person.html(selectedItem.data.pubName);

            tmp_date.html(selectedItem.data.addDate.toString().split(' ')[0].replaceAll('/', '-').toString());

 

            btnTitle.click(function () {

                var heart_date = "";

                if (selectedItem.data.beginDate.toString() == selectedItem.data.endDate.toString()) {

                    heart_date = selectedItem.data.beginDate.toString().split(' ')[0].replaceAll('/', '-');

                }

                else {

                    heart_date = selectedItem.data.beginDate.toString().split(' ')[0].replaceAll('/', '-') + " 至 " + selectedItem.data.endDate.toString().split(' ')[0].replaceAll('/', '-');

                }

                $("#heart_title").html(selectedItem.data.title);

                $("#heart_content").html(selectedItem.data.content);

                $("#heart_date").html(heart_date);

                $("#heart_person").html(selectedItem.data.participator);

                $("#heart_contact").html(selectedItem.data.contact);

                $("#heatr_puber").html(selectedItem.data.pubName);

                //ShowBox

                this.href = "#heartInfo_content";

                $(this).addClass("heartInfo_inline");

                $("#heartInfo_content").show();

                showDialog();

            });

        });

    });

}

JS数据绑定模板artTemplate试用的更多相关文章

  1. js数据绑定(模板引擎原理)

    <div> <ul id="list"> <li>11111111111</li> <li>22222222222< ...

  2. JS之模板技术(aui / artTemplate)

    artTemplate是个好东西啊,一个开源的js前端模板引擎,使用简单,渲染效率特别的高. 我经常使用这个技术来在前端动态生成新闻列表,排行榜,历史记录等需要在前端列表显示的信息. 下面是artTe ...

  3. 【每天半小时学框架】——React.js的模板语法与组件概念

           [重点提前说:组件化与虚拟DOM是React.js的核心理念!]        先抛出一个论题:在React.js中,JSX语法提倡将 HTML 和 CSS 全都写入到JavaScrip ...

  4. Vue.js 数据绑定语法详解

    Vue.js 数据绑定语法详解 一.总结 一句话总结:Vue.js 的模板是基于 DOM 实现的.这意味着所有的 Vue.js 模板都是可解析的有效的 HTML,且通过一些特殊的特性做了增强.Vue ...

  5. js使用模板快速填充数据

    1.html <!DOCTYPE html> <html> <head> <title>模板标签</title> </head> ...

  6. js 简单模板引擎

    代码 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" cont ...

  7. js模板 arttemplate 让数据与html分离

    js模板引擎 前后交互过程中最麻烦的就是如何将json数据展示到页面中,循环拼接html的方法实在是太low了,饱受其苦,BAT同样会遇到这样的问题,于是乎就有个各自的js模板引擎,目的只有一个:让数 ...

  8. Vue.js双向数据绑定模板渲染

    准备知识 1. 前端开发基础 html.css.js2. 前端模块化基础3. 对ES6有初步的了解 vuejs官网:cn.vuejs.org HTML: <!DOCTYPE html> & ...

  9. 前端模板artTemplate,handlerbars的使用心得

    写前端页面肯定离不开模板渲染,就近期项目中用的两个前端模板做一些使用总结,顺便复习一下,也方便后面温故. 1,artTemplate 优点: 1,一般web端用得较多,执行速度通常是 Mustache ...

随机推荐

  1. lua5.1 和 5.2 关于 sequence 的定义变化,对#table取值的影响

    引子 环境 lua 5.2 a = {}   for i=1,2 do a[i] = i*3 end   a[4] = 11;   print(a[#a])   ---print 11 ------- ...

  2. 使用crontab创建 linux 系统定时任务#

    任务1: 每隔1分钟,运行一次 /home/sn/yeelink.sh文件 ,用于上传数据到www.yeelink.net 1. 先在当时目录里面创建一个cronfile文件 vim cronfile ...

  3. 9、Cocos2dx 3.0游戏开发找小三之工厂方法模式与对象传值

    重开发人员的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/27704153 工厂方法模式 工厂方法是程序设计中一个 ...

  4. Lua相关的知识

    http://stackoverflow.com/questions/5438751/how-to-debug-lua-remotely http://cn.bing.com/search?q=org ...

  5. rhel5.8 ISO yum源配置

    [root@lei1 mnt]# mkdir /mnt/iso [root@lei1 mnt]# mkdir /mnt/cdrom [root@lei1 ~]# mv rhel-server-5.8- ...

  6. Netty+Tomcat热部署端口占用解决办法(转)

    在eclipse使用maven deploy (tomcat:deploy) 热部署netty项目 ,项目启动的时候会报错端口被占用. java.net.BindException: Address  ...

  7. RH033读书笔记(11)-Lab 12 Configuring the bash Shell

    Sequence 1: Configuring the bash Shell Deliverable: A system with new aliases that clear the screen, ...

  8. 黑马程序员—创建JDBC框架及原理分析

    对于Java数据库的连接,由最初学习的每次全部手工代码,到后面的不断利用知识简化代码量:这是不断学习的过程,就像人类由原始社会的钻木取火到当代的文明,都是一步步过来的! 本文不从最开始的JDBC入门开 ...

  9. Java读取图像和网络存储

    该公司最近在搞一个Web工程,需要下载网络图片,那么既然恢复了一些最基本的东西.数据传输不同的流,简单,很容易下载网络打破了样品的图片,代码非常easy.贡献给大家! 结论,图片主要就四步: 1:拿到 ...

  10. win7下go web之revel

    win7下go web之revel安装   接着上回记录的win7下go环境搭建,go的开发,现在除了sublime外,LiteIDE比较推荐,下载链接 下载安装后直接打开,需要配置下go环境(本机使 ...