conta's diary

思ったこと、やったことを書いてます。 twitter: @conta_

Ember.jsの外部templateファイル読み込み

忘れないうちにメモ。
これでいいのかはわからないけど、一応動いた。templateファイルを合体してひとつのファイルにすればいいんだけど、なんかやってみたかったのでやってみた。

ファイル構成

こんな感じ

app/
  index.html
  js/
    app.js
    libs/
      jquery.js
      ember.js
  templates/
    hello.handlebars

app.js

読み込みファイルの追加は、templatesにtemplateのファイル名を書いていく。
$ajaxのasyncをfalseにしないと、templateを読み込む前にjsが実行されてしまってエラーになる。
なんかもっといい解決策があるかもしれない。

function fetchResources(url, callback) {
  $.ajax(
    {
      type: "GET",
      url: url,
      async: false,
      dataType: "text",
      success: function(data) {
        console.log("fetch template:", data);
        callback(null, data);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.error(XMLHttpRequest, textStatus, errorThrown);
        var err = {
          message: textStatus,
          error: errorThrown
        };
        callback(err, null);
      }
    });
}

function fetchTemplate(templateName) {
  var url = 'templates/' + templateName + '.handlebars';
  fetchResources(url,
                 function(err, data) {
                   if(err) {
                     console.error(err);
                     return;
                   }
                   if (Ember.TEMPLATES[templateName]) {
                     console.log(url + 'is already fetched');
                     return;
                   }

                   Em.TEMPLATES[templateName] = Em.Handlebars.compile(data);

                 });
}

var App = Em.Application.create();
App.ready = function() {
  console.log('App.ready()');
};

var templates = ['hello'];

templates.forEach(function(tmpName) {
  fetchTemplate(tmpName);
});

App.HelloView = Em.View.extend(
  {
    templateName: 'hello',
    name: "World!"
  });

hello.handlebars

<h1>hello, {{name}}</h1>

index.htmlのぼでー

<body>
  <script type="text/x-handlebars">
    {{view App.HelloView}}
  </script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>
  <script src="js/libs/ember-0.9.8.1.min.js"></script>
  <script src="js/app.js"></script>
</body>

templateNameのところにtemplateのurlを書くだけで出来ればいいのに(´・ω・`)