如何与骨干同步加载外部模板

时间:2012-10-09 19:31:06

标签: javascript backbone.js coffeescript sprockets

我正在尝试使用phonegap,backbone.js和coffeescript构建移动应用程序。我想做这样的事情:

class MyApplication.Views.EntriesIndex extends Backbone.View
  template: load('my/template') //It will load the external file my/template.tpl

  render: ->
    $(@el).html(@template())
    this

我想同步加载它。我已经看过require.js,但我觉得这个简单的想法太复杂了。我看到我可以将JST用于rails应用程序,但是我没有找到如何在没有链轮的情况下使用它,我的应用程序必须只在客户端工作。

同步加载模板的更好方法是什么?

我认为更好的是预加载它。

我的应用程序将托管在客户端。

3 个答案:

答案 0 :(得分:1)

我以这种方式加载我的模板:

         $.ajax({
            url     : 'my/template.tpl',
            async   : false,
            success : function(tpl) {
                //do something with the template
            }
        });

也许它是一个适合你的解决方案..

答案 1 :(得分:1)

我这样做了:

class HomeView extends Backbone.View
  template: ->
    template = "views/home.html"
    cache = window.templates[template]
    return cache if cache

    cache = $.ajax(
      url: "views/home.html"
      async: false).responseText

    window.templates[template] = cache
    return cache

  render: ->
    @$el.html(@template())

而且,在我的应用程序的初始化中:

window.templates = {}

所以我可以异步加载模板并缓存它。显然,我会做一些重构,可能会把它放到JQuery函数中。

感谢您的帮助。

修改

我更改了我的代码来执行此操作:

class Loader
  @files: {}
  @load: (path) ->
    return @files[path] ||= $.ajax(url: path, async: false).responseText

现在我可以这样做:

class HomeView extends Backbone.View
  template: ->
    Loader.load("views/home.html")

  render: ->
    @$el.html(@template())

这是javascript的版本:

var Loader;

Loader = (function() {

  function Loader() {}

  Loader.files = {};

  Loader.load = function(path) {
    var _base;
    return (_base = this.files)[path] || (_base[path] = $.ajax({
      url: path,
      async: false
    }).responseText);
  };

  return Loader;

})();

我可能会在github上发布代码......

答案 2 :(得分:0)

如果您的应用程序作为phonegap应用程序运行,您可以在HTML中包含您的模板:

Explanation of <script type = "text/template"> ... </script>