JavaScriptクライアントサイドテンプレートエンジン(続き)

一昨日の続きです。

その後修正を加えたバージョンを公開します。

やったこと:

  1. 外部JS化しました。
  2. dataをcontrollerにしました。
  3. HTMLタグの出力と、属性の変更も実装してみました。

TeplateEngine.js (仮のファイル名)

TemplateEngine = new function() {
this.currentNode;
this.writeText = function (value) { return new WriteText(value); };
this.writeHtml = function (value) { return new WriteHtml(value); };
this.setAttribute = function (name, value) { return new SetAttribute(name, value); };
function WriteText(value) {
this.execute = execute;
function execute() {
TemplateEngine.currentNode.text(value);
}
}
function WriteHtml(value) {
this.execute = execute;
function execute() {
TemplateEngine.currentNode.html(value);
}
}
function SetAttribute(name, value) {
this.execute = execute;
function execute() {
TemplateEngine.currentNode.attr(name, value);
}
}
}
TemplateEngineRunner = new function() {
this.run = run;
function run(controller) {
for (var key in controller) {
TemplateEngine.currentNode = $('#' + key);
controller[key].execute();
}
}
}

test.html

<!DOCTYPE html>
<html lang="ja">
<head>
   <meta charset="utf-8">
   <title>Template Engine Test</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<span id="test"></span>
<span id="testHtml"></span>
<span id="attr">test</span>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.4.2");</script>
<script type="text/javascript" src="templateEngine.js"></script>
<script>
   var controller = {
       test: TemplateEngine.writeText('hoge<b>aaa</b>'),
       testHtml: TemplateEngine.writeHtml('<i>aaa</i>'),
       attr: TemplateEngine.setAttribute('style', 'font-weight: bold;')
   }
   
   TemplateEngineRunner.run(controller);
</script>
</body>
</html>

試してみると、Google AJAX APIを使ったためか、JSをロードして置換を始めるまで待ち時間がちょっとありますね。dummyといった文字列を出すのはあまりよくなさそうなので、普通に空欄にした方が良いと思いました。本当は、この程度のことならjQueryもいらないんですよね。

続く

コメントを残す