原型 - 模板
模板用於格式化一組類似的物件,併為這些物件生成格式化的輸出。
Prototype 提供了一個 Template 類,它有兩個方法:
Template() - 這是一個構造方法,用於建立模板物件並呼叫 evaluate() 方法來應用模板。
evaluate() - 此方法用於應用模板來格式化物件。
建立格式化輸出涉及三個步驟。
建立模板 - 這涉及建立預格式化的文字。此文字包含格式化的內容以及 #{fieldName} 值。當使用實際值呼叫 evaluate() 方法時,這些 #{fieldName} 值將被實際值替換。
定義實際值 - 這涉及以鍵值對的形式建立實際值。這些鍵將在模板中對映,並被相應的替換。
對映鍵並替換值 - 這是最後一步,其中將呼叫 evaluate(),並且格式化物件中所有可用的鍵將被定義的值替換。
示例 1
步驟 1
建立一個模板。
var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');
步驟 2
準備我們的值集,這些值將傳遞到上面的物件以獲得格式化的輸出。
var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];
步驟 3
最後一步是在模板中填充所有值,併產生如下最終結果:
records.each( function(conv) {
alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});
所以,讓我們將這三個步驟放在一起:
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
<script>
function showResult() {
// Create template with formatted content and placeholders.
var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');
// Create hashes with the required values for placeholders
var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];
// Now apply template to produce desired formatted output
records.each( function(conv) {
alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});
}
</script>
</head>
<body>
<p>Click the button to see the result.</p>
<br />
<br />
<input type = "button" value = "Result" onclick = "showResult();"/>
</body>
</html>
這將產生以下結果:
輸出
廣告