Prototype Template对象 学习_prototype

复制代码 代码如下:

var Template = Class.create({
//初始化方法
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},

//格式化方法,如果从java的角度来说,其实叫format更好 :)
evaluate: function(object) {
    //检查是否定义了toTemplateReplacements方法,是的话调用
    //整个的Prototype框架中,只有Hash对象定义了这个方法
if (object && Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();

    //这里的gsub是String对象里面的方法,可以简单的认为就是替换字符串中所有匹配pattern的部分
return this.template.gsub(this.pattern, function(match) {
//match[0]是整个的匹配Template.Pattern的字符串
     //match[1]是匹配字符串前面的一个字符
     //match[2]是匹配${var}这个表达式的部分
     //match[3]是'#{var}'表达式的'var'部分

     //如果object为null,则把所有的${var}表达式替换成''
if (object == null) return (match[1] + '');

     //取得匹配表达式前一个字符
var before = match[1] || '';
     //如果前一个字符串为'\',则直接返回匹配的表达式,不进行替换
if (before == '\\') return match[2];

var ctx = object, expr = match[3];
     //这个正则表达式好像就是检查var是否是合法的名称,暂时没看懂这个正则表达式的意义?
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
     //如果var不符合要求,则直接返回前一个字符
if (match == null) return before;
//逐个替换'#{var}'表达式部分
while (match != null) {
         //不懂下面这个检查什么意思?
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
     //返回替换后的结果,'#{var}' ==> 'value'
return before + String.interpret(ctx);
});
}
});
//默认的模板匹配正则表达式,形如#{var},很像JSP中的EL表达式
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

上面基本上把evaluate方法讲了一遍,有些地方没怎么看明白,那些正则表达式太难懂了。。。谁知道的告诉我?

下面看一下示例:

复制代码 代码如下:

var myTemplate = new Template('The TV show #{title} was created by #{author}.');

var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };

myTemplate.evaluate(show);
// -> The TV show The Simpsons was created by Matt Groening.

复制代码 代码如下:

var t = new Template('in #{lang} we also use the \\#{variable} syntax for templates.');
var data = {lang:'Ruby', variable: '(not used)'}; t.evaluate(data);
// -> in Ruby we also use the #{variable} syntax for templates.

复制代码 代码如下:

//自定义匹配模式
var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/;

//matches symbols like '<%= field %>'
var t = new Template('<div>Name: <b><%= name %></b>, Age: <b><%=age%></b></div>', syntax);

t.evaluate( {name: 'John Smith', age: 26} );
// -> <div>Name: <b>John Smith</b>, Age: <b>26</b></div>

复制代码 代码如下:

var conversion1 = {from: 'meters', to: 'feet', factor: 3.28};
var conversion2 = {from: 'kilojoules', to: 'BTUs', factor: 0.9478};
var conversion3 = {from: 'megabytes', to: 'gigabytes', factor: 1024};

var templ = new Template('Multiply by #{factor} to convert from #{from} to #{to}.');

[conversion1, conversion2, conversion3].each( function(conv){ templ.evaluate(conv); });
// -> Multiply by 3.28 to convert from meters to feet.
// -> Multiply by 0.9478 to convert from kilojoules to BTUs.
// -> Multiply by 1024 to convert from megabytes to gigabytes.

时间: 2024-08-02 04:50:51

Prototype Template对象 学习_prototype的相关文章

Prototype Selector对象学习_prototype

复制代码 代码如下: function $$() { return Selector.findChildElements(document, $A(arguments)); } 这个类可以分成三个部分:第一个部分就是根据不同的浏览器,判断使用什么DOM操作方法.其中操作IE就是用普通的getElementBy* 系列方法:FF是document.evaluate:Opera和Safari是selectorsAPI.第二部分是对外提供的基本函数,像findElements,match等,Eleme

Prototype Class对象学习_prototype

复制代码 代码如下: /* Based on Alex Arnell's inheritance implementation. */ var Class = (function() { //临时存储parent的prototype function subclass() {}; //创建类的方法 function create() { var parent = null, properties = $A(arguments);     //检查新建一个类时,是否指定了一个父对象     //如

Prototype Object对象 学习_prototype

Object is used by Prototype as a namespace; that is, it just keeps a few new methods together, which are intended for namespaced access (i.e. starting with "Object."). 上面说的namespace个人理解就相当于C#中的静态类,提供工具函数的意思,和C#中的namespace应该不是一个概念.因为C#中的命名空间后面不会直

Prototype ObjectRange对象学习_prototype

Ranges represent an interval of values. The value type just needs to be "compatible," that is, to implement a succ method letting us step from one value to the next (its successor). Prototype provides such a method for Number and String, but you

Prototype Function对象 学习_prototype

这个对象就是对function的一些扩充,最重要的当属bind方法,prototype的帮助文档上特意说了一句话:Prototype takes issue with only one aspect of functions: binding.其中wrap方法也很重要,在类继承机制里面就是利用wrap方法来调用父类的同名方法.argumentNames bind bindAsEventListener curry defer delay methodize wrap 复制代码 代码如下: //通

Prototype Array对象 学习_prototype

复制代码 代码如下: Array.from = $A; (function() { //Array原型的引用     var arrayProto = Array.prototype, slice = arrayProto.slice,      //JS 1.6里面会有原生的forEach方法 _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available function each(it

Prototype Hash对象 学习_prototype

复制代码 代码如下: //Hash对象的工具函数 function $H(object) { return new Hash(object); }; var Hash = Class.create(Enumerable, (function() { //初始化,创建一个新的Hash对象 function initialize(object) { this._object = Object.isHash(object) ? object.toObject() : Object.clone(obje

Prototype Date对象 学习_prototype

看一下源码: 复制代码 代码如下: Date.prototype.toJSON = function() { return '"' + this.getUTCFullYear() + '-' + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + this.getUTCDate().toPaddedString(2) + 'T' + this.getUTCHours().toPaddedString(2) + ':' + this.getUTCM

Prototype PeriodicalExecuter对象 学习_prototype

This is a simple facility for periodical execution of a function. This essentially encapsulates the native clearInterval/setInterval mechanism found in native Window objects. This is especially useful if you use one to interact with the user at given