【问题标题】:How to load external template synchronously with backbone如何与主干同步加载外部模板
【发布时间】:2012-09-30 04:49:17
【问题描述】:

我正在尝试使用 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 应用程序,但我不知道如何在没有 sprocket 的情况下使用它,而且我的应用程序必须只能在客户端工作。

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

我认为最好是预加载它。

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

【问题讨论】:

  • 您是否尝试过将异步设置为 false 的 $.ajax?假设您使用的是 jQuery
  • 您的应用程序是托管在客户端还是服务器上(phonegap 基本上只是包装它)?
  • 我必须在初始化时加载模板,成功时存储它并缓存它以仅加载一次?嗯,这可以是一个解决方案。有没有更好的办法?它认为更好的解决方案是预编译它。
  • 我的应用程序将托管在客户端。我更新了我的问题。
  • 如果您正在寻找更好的方法,请使用 require.js。在开发中,它会在需要时自动加载所有模板,在生产中,您可以将其编译为单个文件并在需要时加载。

标签: javascript backbone.js coffeescript sprockets


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我这样做了:

    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上发布代码...

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我已经看过了,但不可能做这样的事情:&lt;script type="text/template" src="my/external/file.tpl"&gt;&lt;script&gt;。我想为更好的架构使用外部文件。
      • @Dougui 不确定这将如何改进您的架构。就个人而言,我使用一个简单的构建工具来内联我的生产模板。在那之前,我在开发过程中使用同步 XHR 调用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      相关资源
      最近更新 更多