我的Js模版引擎(四)

上次的js模版引擎在ie6,7下总是发生错误,今天用ie8的调试工具终于找到了错误的根源所在,原来是自己多写了一个逗号,真囧!

这次的模版引擎基本没啥大问题了,全面兼容ie6,7,8 ff,opera各大主流浏览器,并且修复了特殊标签}}}的bug,ok,直接上demo吧。

 

模版引擎核心代码

/**
 * @author hust_小C
 * email:hustcoolboy@gmail.com
 */
(function(w){
          var dom = {
                    quote: function (str) {
                        str = str.replace(/[\x00-\x1f\\]/g, function (chr) {
                            var special = metaObject[chr];
                            return special ? special : '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4)
                        });
						return str.replace(/"/g, '\\"') ;
                     
                    }
                },
                metaObject = {
                    '\b': '\\b',
                    '\t': '\\t',
                    '\n': '\\n',
                    '\f': '\\f',
                    '\r': '\\r',
                    '\\': '\\\\'
                };
//上边的dom来自司徒正美http://www.cnblogs.com/rubylouvre/


 w.Template=Template||{}; function Template(options){ return this instanceof arguments.callee?this.init(options):new arguments.callee(options); } Template.parse=function(self){ var temp; if(self.right=="}}"){//这里主要是为了解决{{{造成的bug! temp=self.tplcontent.replace(/(}})([^}])/g,function(){ return arguments[1]+" "+arguments[2]; }).split(new RegExp('(?='+self.left+')|('+self.right+')(?:[^}])')) }else{ temp=self.tplcontent.split(new RegExp('(?='+self.left+')|('+self.right+')')) } temp.filter(function(k,v){ return !(new RegExp(self.right)).test(v); }).each( function(k,v){ if((new RegExp('^'+self.left)).test(v)){ if(new RegExp('^'+self.left+'\s*=').test(v)){ self.body.push(v.replace(new RegExp('^'+self.left+'\s*=(.*)'),'\ttemp.push($1);\n').replace(/\\n/g,'')); }else{ self.body.push(v.replace(new RegExp('^'+self.left+'\s*(.*)'),'$1\n').replace(/\\n/g,'')); } } else {self.body.push('\ttemp.push(\"'+v.replace(/\n|\t/g,'')+'\");\n');} }) return self.body.join(""); }; Template.prototype={ init:function(options){ this.tpl=options.tpl;//待解析的模版 this.target=options.target||options.tpl;//解析后渲染的模板dom this.tplcontent=dom.quote(options.tpl.text||options.tpl.value); this.left=options.left||"{{";//左分隔符 this.right=options.right||"}}";//右分隔符 this.namespace=options.namespace||"data";//编译生成的函数,里边所用变量的环境,即模版中所用变量的执行环境 this.body=[]; this.compiled="";//编译生成的函数 this.data=options.data; }, compile:function(){ if(!this.compiled){ this.compiled=new Function(this.namespace,'var temp=[];\n'+Template.parse(this)+'\n return temp.join("");'); } return this.compiled; }, render:function(){ this.target.innerHTML=this.compile()(this.data); } } })(this); Array.prototype.filter=function(fn){ var temp=[]; for(var i=0,l=this.length;i<l;i++){ this[i]&&fn.call(this,i,this[i])&&temp.push(this[i]); } return temp; } Array.prototype.each=function(fn){ var temp=[]; for(var i=0,l=this.length;i<l;i++){ fn.call(this,i,this[i]); } return this; } document.getElementById('render').onclick=function(){ Template({tpl:document.getElementById('tpl'),target:document.getElementById('ok'),data:{a:{ name:"coolboy", age:21, test:"good!" }, b:100, url:["http://image9.9158.com/39/37/1402184341/971BA9080689FCF08A61948AC224115C.jpg","http://image9.9158.com/43/36/928573648/C6703ED2CCF75829B050D9F0ED8BB274.jpg","http://image9.9158.com/35/43/1792415536/5CB6C5F949CB9DF3E3A30BA871970002.jpg"], song:[{songname:"千百度 ",singer:"许嵩",url:"http://zhangmenshiting.baidu.com/data/music/4752698/%E5%8D%83%E7%99%BE%E5%BA%A6.mp3?xcode=f08fdfd64a17ddb73c350b4e1ff22833"},{songname:"想象之中",singer:"许嵩",url:"http://zhangmenshiting.baidu.com/data/music/4753398/%E6%83%B3%E8%B1%A1%E4%B9%8B%E4%B8%AD.mp3?xcode=9354de7edd267ba005efbff149ebffea"}, {songname:"半城烟沙",singer:"许嵩",url:"http://zhangmenshiting.baidu.com/data/music/264925/%E5%8D%8A%E5%9F%8E%E7%83%9F%E6%B2%99.mp3?xcode=cf43709031889621fd7bc075c0ef2950"}, {songname:"最熟悉的陌生人",singer:"萧亚轩",url:"http://media.openedu.com.cn/media_file/netcourse/asx/mxyl/public/mxjs/music/4.MP3"}] }}).render(); }

介绍下处理}}}bug的方法吧,基本思想是这样的

比如一个字符串str="12345}}}'789",我需要把它分割成一个数组[12345},'789],简单的str.split(/}}/)无法达到我要的效果,

这样也不行str.split(/}}(?:[^}])/)

要保留上边的’符号,可以先对字符串进行一下处理str=str.replace(/(}})([^}])/g,function(){
        return arguments[1]+"   "+arguments[2];
     }),处理后再split就ok啦!

posted @ 2011-04-28 22:36  淘小杰  阅读(5705)  评论(1编辑  收藏  举报